我正在尝试从 Android 应用程序覆盖文本文件,我已经完成的是,
我在一项 Activity 中使用以下方法创建了一个文本文件:
FileOutputStream create_file = null;
OutputStreamWriter osw = null;
create_file = openFileOutput("filename.txt", Context.MODE_WORLD_WRITEABLE);
osw = new OutputStreamWriter(create_file);
osw.write("text goes here");
osw.close();
create_file.close();
我已经在另一个 Activity 中打开该文件,使用以下方法逐行读取内容:
FileInputStream open_file = openFileInput("filename.txt");
InputStreamReader isr = new InputStreamReader(open_file);
BufferedReader inRd = new BufferedReader(isr);
while ((getText = inRd.readLine()) != null)
{
Toast.makeText(getApplicationContext(), getText, Toast.LENGTH_SHORT).show();
}
通过此操作,我验证了内容是否已存储,并确保该文件与内容一起存在,但是当我尝试使用以下方法从另一个 Activity 覆盖该文件时:
FileOutputStream create_file = null;
OutputStreamWriter osw = null;
create_file = new FileOutputStream(new File(PasswordUtil.pswrd_file), false);
osw = new OutputStreamWriter(create_file);
osw.write(getString);
我遇到一个异常,
java.io.FileNotFoundException:/ filename.txt (Read-only file system)
注意:文本文件存储在内部存储中。
任何帮助,提前致谢。
最佳答案
我找到了原因FileNotFoundException
,这是因为而不是以下行:
create_file = new FileOutputStream(new File("filename.txt", false));
我们必须指定该文件的路径,对于我来说,我已将其存储在内部存储中,并且我给出了路径
"/data/data/<Package-Name>/files/" + "filename.txt"
我已经像这样更改了覆盖编码,
FileOutputStream overWrite = new FileOutputStream("/data/data/<Package-Name/files/" + "filename.txt", false);
overWrite.write(getString.getBytes());
overWrite.flush();
overWrite.close();
现在一切正常。
关于android - 以编程方式覆盖文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5178873/