我的文本文件conten.txt
有
101,1,123
102,1,234
我使用Android来更新该文本文件。输入为" 102",我想更新第二行,信息是" 2,234"。所以它将是
102,2,234
最后,文本文件中的内容将是
101,1,123
102,2,234
是否可以在Android中执行此操作?这是我目前的工作。但是,tt只在文件中写入一个新行
String whole_content="102,2,234";
File file = new File(getApplicationContext().getFilesDir(), "conten.txt");
String filepath = Environment.getExternalStorageDirectory().getPath();
FileOutputStream outputStream;
try {
outputStream = openFileOutput("conten.txt", Context.MODE_PRIVATE);
outputStream.write(whole_content.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:1)
是的,这是可能的!简单地说,您可以创建一个总文件内容的字符串,并替换字符串中的所有匹配项,并再次将该字符串写入该文件。
File log= new File("yourFile");
String search = "102"; //Like you said
try{
FileReader fr = new FileReader(log);
String s;
String totalStr = "";
try (BufferedReader br = new BufferedReader(fr)) {
while ((s = br.readLine()) != null) {
if(s.contain(search)) {
s = search + "," + "yourReplaceString"; //You can extract it from your input
}
totolStr += s;
}
FileWriter fw = new FileWriter(log);
fw.write(totalStr);
fw.close();
}
}catch(Exception e){
e.printStackTrace();
}