1

This following code snippet seems to create a file successfully, and the writeData function writes to the StringWriter appropriately, however the file seems to be empty..

fileOutputStream = new FileOutputStream(selectedFile);

if(!selectedFile.exists())
    selectedFile.createNewFile();


StringWriter writer = new StringWriter();
serializer.setOutput(writer);

Log.i(TAG, "- Output is asigned to the special Serializer object");     

/* The target data is written to the a string buffer in the StringWriter */
writeData(serializer, templateData); 

Log.i(TAG, String.format("- New file Data written: %s", writer.toString())); // Logcat prints the file data from this string beautifully..      

fileOutputStream.write(writer.toString().getBytes()); // Not happening?! Why :(
fileOutputStream.close();

The String is definately not empty!

The file created however, is empty! I've also tried variations with OuputStreamWriter and the like but the file is not written into. Why? I am testing this on a Nexus 7 tablet and I have the WRITE_EXTERNAL_STORAGE permission set.

Update: All the files are created in this process. The access permission of the file is created as "_rw".

Other methods I've used that give exactly the same result:

FileWriter fw = new FileWriter(selectedFile.getPath());
fw.write(writer.toString());
fw.flush();
fw.close();

In all cases, a file is created via createNewFile() however no data is ever written to it. The app carries on as normal without throwing anything. I just don't understand :'(

user965369
  • 5,413
  • 13
  • 33
  • 47

2 Answers2

0
FileOutputStream fOut = openFileOutput(selectedFile);//u can use (filename, Context.MODE_APPEND | Context.MODE_WORLD_READABLE)

if(!selectedFile.exists())
    selectedFile.createNewFile();

OutputStreamWriter osw = new OutputStreamWriter(fOut);
      osw.append(templateData);
      osw.flush();
      osw.close();
Sardor Dushamov
  • 1,665
  • 3
  • 17
  • 44
  • I've also tried this method - doesn't seem to work either! This is so frustrating there must be something bigger going on here. – user965369 Oct 17 '12 at 17:18
0

If you're calling FileOutputStream.FileOutputStream(File) after you've written to the file all the data will be erased. Check out this thread: How to write data with FileOutputStream without losing old data?

Community
  • 1
  • 1
user965369
  • 5,413
  • 13
  • 33
  • 47