简体   繁体   English

无法在Android中写入文件

[英]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.. 下面的以下代码片段似乎成功创建了一个文件,并且writeData函数适当地写入了StringWriter ,但是该文件似乎为空。

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. 我还尝试了使用OuputStreamWriter之类的变体,但未将文件写入。 Why? 为什么? I am testing this on a Nexus 7 tablet and I have the WRITE_EXTERNAL_STORAGE permission set. 我正在Nexus 7平板电脑上对此进行测试,并且设置了WRITE_EXTERNAL_STORAGE权限。

Update: All the files are created in this process. 更新:所有文件都在此过程中创建。 The access permission of the file is created as "_rw". 文件的访问许可被创建为“ _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. 在所有情况下,都是通过createNewFile()创建文件的,但是从未写入任何数据。 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. 如果在写入文件后调用FileOutputStream.FileOutputStream(File),则所有数据将被删除。 Check out this thread: How to write data with FileOutputStream without losing old data? 看看这个线程: 如何在不丢失旧数据的情况下使用FileOutputStream写入数据?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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