我们可以通过输入输出流向文件中追加内容.本文记录使用java修改,向指定位置前后添加内容的方法.
To edit file in java we need to search text which replace with
new text. indexOf() method will search text in java and append()
method will modify old content in string.
修改前文本文件中的内容
hello abc, goodbye xyz
完整代码:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class JavaIOEditFileExample {
public static void main(String[] args) {
File f = new
File("c:\\appendOldFile.txt");
FileInputStream fs =
null;
InputStreamReader in =
null;
BufferedReader br =
null;
StringBuffer sb = new
StringBuffer();
String textinLine;
try {
fs = new
FileInputStream(f);
in = new
InputStreamReader(fs);
br = new
BufferedReader(in);
while
(true) {
textinLine = br.readLine();
if (textinLine == null)
break;
sb.append(textinLine);
}
String
textToEdit1 = "abc";
int cnt1 =
sb.indexOf(textToEdit1);
sb.replace(cnt1, cnt1 + textToEdit1.length(), "码农");
String
textToEdit2 = "xyz";
int cnt2 =
sb.indexOf(textToEdit2);
sb.replace(cnt2, cnt2 + textToEdit2.length(), textToEdit2
+ " and 哈利波特");
fs.close();
in.close();
br.close();
} catch
(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
try {
FileWriter
fstream = new FileWriter(f);
BufferedWriter outobj = new BufferedWriter(fstream);
outobj.write(sb.toString());
outobj.close();
System.out.println("Done");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
修改后文件中的内容
hello 码农, goodbye xyz and 哈利波特
加载中,请稍候......