简体   繁体   中英

Can't write to file in Android

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 :'(

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();

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM