这是我的写入方法的代码片段,当我想将数据写入此文件时,我可以调用该代码片段。
public void Write(String file,String data) {
File rootsd= Environment.getExternalStorageDirectory();
File datafolder= new File(rootsd.getAbsolutePath()+"/Data");
if(!datafolder.isDirectory())
{
try
{
datafolder.mkdir();
}
catch (Exception e)
{
Log.e("Error","Directory was not created");
}
}
File datafile= new File(datafolder,file);
try {
if (!datafile.exists())
{
datafile.createNewFile();
}
writer = new BufferedWriter(new FileWriter(datafile));
writer.write(data);
writer.close();
}
catch (Exception e) {
Log.e("Error", "File not found");
}
}
由于某种原因,这会自动进入catch异常并返回File not Found,我不太清楚问题是什么,我似乎无法在线找到解决方案。感谢所有帮助,谢谢!
编辑:Logcat异常
Caused by: java.io.IOException: open failed: ENOENT (No such file or directory)
at java.io.File.createNewFile(File.java:941)
at uwpsych.ocdstopwatch.Q1.Write(Q1.java:157)
at uwpsych.ocdstopwatch.Q1.SaveData(Q1.java:142)
at java.lang.reflect.Method.invoke(Native Method)
答案 0 :(得分:0)
在AndroidManifest.xml
添加
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
如果你想阅读文件add和
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />