我正在尝试使用以下代码写入 Android 应用程序中的文件:
File save = new File("sdcard/save.txt");
if(!save.exists()) {
try {
save.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream fos = new FileOutputStream(save);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("1");
osw.flush();
osw.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
但是,我的调试器在 osw.close();
行之后转到 IOException
问题是那个阶段 e
不存在,所以我无法读取异常消息。
我在androidManifest.xml 中添加了正确的premission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
但它不起作用。
最佳答案
File save = new File("sdcard/save.txt"); is bad code
使用下面的代码
String path= Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
File file = new File(path + File.separator + fileName);
关于java - 写入文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11936231/