我有一个按钮,我想在onClick方法中创建一个文件,但我总是得到一个FileNotFoundException
。写入内部存储的权限已经在manifest.xml
以下是代码:
registerButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
bufferedWriter = new BufferedWriter(new FileWriter("sample.txt"));
bufferedWriter.write(getString(R.string.emailString));
bufferedWriter.newLine();
bufferedWriter.write(getString(R.string.passwordString));
System.out.println("Done!");
}
catch (IOException e)
{
e.printStackTrace();
Log.d("MainActivity", "Bad luck!");
}
finally
{
try
{
if(bufferedWriter != null)
bufferedWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
Log.d("MainActivity", "Sorry for that!");
}
}
}
});
以下是错误日志
03-28 01:00:11.537: W/System.err(2610): java.io.FileNotFoundException: /sample.txt: open failed: EROFS (Read-only file system)
03-28 01:00:11.557: W/System.err(2610): at libcore.io.IoBridge.open(IoBridge.java:406)
03-28 01:00:11.557: W/System.err(2610): at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
03-28 01:00:11.567: W/System.err(2610): at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
03-28 01:00:11.588: W/System.err(2610): at java.io.FileWriter.<init>(FileWriter.java:80)
03-28 01:00:11.588: W/System.err(2610): at
org.eirich.way.MainActivity$1.onClick(MainActivity.java:34)
03-28 01:00:11.607: W/System.err(2610): at android.view.View.performClick(View.java:3480)
03-28 01:00:11.607: W/System.err(2610): at android.view.View$PerformClick.run(View.java:13983)
03-28 01:00:11.628: W/System.err(2610): at android.os.Handler.handleCallback(Handler.java:605)
03-28 01:00:11.628: W/System.err(2610): at android.os.Handler.dispatchMessage(Handler.java:92)
03-28 01:00:11.647: W/System.err(2610): at android.os.Looper.loop(Looper.java:137)
03-28 01:00:11.667: W/System.err(2610): at android.app.ActivityThread.main(ActivityThread.java:4340)
03-28 01:00:11.667: W/System.err(2610): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 01:00:11.687: W/System.err(2610): at java.lang.reflect.Method.invoke(Method.java:511)
03-28 01:00:11.687: W/System.err(2610): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
答案 0 :(得分:3)
在内部存储中创建文件:
bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+"/sample.txt")));
因为目前你没有使用file.use getFilesDir()传递目录路径,它返回文件系统上目录的绝对路径
答案 1 :(得分:1)
这是因为您没有将目录路径传递给FileWriter
。
使用:
bufferedWriter = new BufferedWriter(new FileWriter(newFile(getFilesDir()+File.separator+"sample.txt")));
相反:
bufferedWriter = new BufferedWriter(new FileWriter("sample.txt"));
即使查看以下链接,也可以为您提供帮助。
Writing/Reading Files to/from Android phone's internal memory
答案 2 :(得分:0)
您可以使用openFileOutput
功能写入内部存储空间:
String string = "My data";
FileOutputStream os = openFileOutput("sample.txt", Context.MODE_PRIVATE);
os.write(string.getBytes());
os.close();
并确保您拥有following permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />