简体   繁体   English

以编程方式覆盖文本文件

[英]Overwrite text file programmatically

I'm trying to overwrite a text file from android application, what I have done yet is, 我正在尝试覆盖android应用程序中的文本文件,但我要做的是,

I have created one text file in one activity using: 我使用以下命令在一项活动中创建了一个文本文件:

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();

and I have opened that file in another activity read the contents line by line using: 并且我在另一个活动中打开了该文件,并使用以下命令逐行读取内容:

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();
}

through this I have verified whether the content is stored or not, and made sure that the file exist with the content, but when I try to overwrite that file from another activity using: 通过此操作,我已经验证了是否存储了内容,并确保文件与内容一起存在,但是当我尝试使用以下方法从另一个活动覆盖该文件时:

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);

I'm getting one exception, 我有一个例外,

java.io.FileNotFoundException:/ filename.txt (Read-only file system)

Note: The text file is stored in Internal storage. 注意:文本文件存储在内部存储器中。

Any help, thanks in advance. 任何帮助,在此先感谢。

I found the reason for that FileNotFoundException , its because instead of the following line: 我找到了该FileNotFoundException的原因,其原因在于,而不是以下行:

create_file = new FileOutputStream(new File("filename.txt", false));

we have to specify the path for that file, for me, I have stored it in internal storage and I gave the path 我们必须指定该文件的路径,对我来说,我已经将其存储在内部存储器中,并且给出了该路径

"/data/data/<Package-Name>/files/" + "filename.txt"

and I've changed the overwrite coding like this, 而且我改变了这样的覆盖编码,

FileOutputStream overWrite = new FileOutputStream("/data/data/<Package-Name/files/" + "filename.txt", false);
overWrite.write(getString.getBytes());
overWrite.flush();
overWrite.close();

now all are working well. 现在一切都很好。

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

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