从内部存储编辑文件 [英] edit file from internal storage
问题描述
如何编辑Android应用程序内部存储中文件的内容.
How can I edit the content of a file located on the internal storage in my Android app.
我要擦除整个内容,然后再次写入文件,而不是将数据附加到当前内容.
I want to erase the whole content and then write to the file again, instead of appending data to the current content.
这是我的读写代码:
package com.example.cargom;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
public class FileManager {
FileOutputStream outputStream;
FileInputStream inputStream;
public void writeToFile(Context context, String fileName, String data) {
try {
outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readFromFile(Context context, String fileName) {
String data = "";
int c;
try {
inputStream = context.openFileInput(fileName);
while ((c = inputStream.read()) != -1) {
data = data + Character.toString((char) c);
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
推荐答案
您的课程已经在执行您要求的工作了.它首先擦除文件的内容,然后在其上写入.为了进一步了解,
Your class is already doing what you rquire. It first erases the contents of the file and then writes on it. For further understanding,
当您使用 MODE_PRIVATE 启动流时,第二次尝试写入文件时,文件中已有的内容将被删除并写入新内容.
When you initiate your stream with MODE_PRIVATE, the second time when you try to write the file, the contents that are already in the file gets erased and the new contents are written.
outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
当您使用 MODE_APPEND 时,已经存在的内容将保留下来,新内容将被追加到文件中.
When you use MODE_APPEND, the contents that are already there stays and the new contents will be appended to the file.
outputStream = context.openFileOutput(fileName, Context.MODE_APPEND);
有关处理内部存储中文件的更多参考信息和详细知识,我建议您观看以下三个简短的视频,为您提供有关演示的详细说明.
For more reference and detailed knowledge on dealing with files in Internal storage, I recommend you to watch the below three short videos which gives you detailed description with demo.
http://www.youtube.com/watch?v = Jswr6tkv8ro& index = 4& list = PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT http://www.youtube.com/watch?v=cGxHphBjTBk&; index = 5& list = PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT http://www.youtube.com/watch?v=mMcrj_To18k&; index = 6& list = PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT
希望有帮助!还有其他问题,请在下面评论.
Hope it helps! Any more questions, please comment below.
这篇关于从内部存储编辑文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!