我见过很多有关此事的帖子,但我无法做到这一点。我需要做这样的事情。让我们说, 我有两个文件a.txt,b.txt。 我应该在a.txt中搜索字符串/行,并将其替换为b.txt的内容。 我认为它几行简单的代码。我尝试了下面的代码,但它不起作用......
File func = new File("a.txt");
BufferedReader br = new BufferedReader(new FileReader(func));
String line;
while ((line = br.readLine()) != null) {
if (line.matches("line to replace")) {
br = new BufferedReader(
new FileReader(func));
StringBuffer whole = new StringBuffer();
while ((line = br.readLine()) != null) {
whole.append(line.toString() + "\r\n");
}
whole.toString().replace("line to replace",
"b.txt content");
br.close();
FileWriter writer = new FileWriter(func);
writer.write(whole.toString());
writer.close();
break;
}
}
br.close();
请帮忙!
答案 0 :(得分:0)
以下是解决此问题的技巧:
答案 1 :(得分:0)
嗯......也许你可以避免创建BufferedReader类的实例并只使用String类:
public class Sample {
public static void main(String[] args) throws Exception{
File afile = new File("/home/mtataje/a.txt");
String aContent = getFileContent(afile);
System.out.println("A content: " );
System.out.println(aContent);
System.out.println("===================");
if (aContent.contains("java rulez")) {
File bfile = new File("/home/mtataje/b.txt");
String bContent = getFileContent(bfile);
String myString = aContent.replace("java rulez", bContent);
System.out.println("New content: ");
System.out.println(myString);
afile.delete();//delete old file
writeFile(myString);//I replace the file by writing a new one with new content
}
}
public static void writeFile(String myString) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/home/mtataje/a.txt")));
bw.write(myString);
bw.close();
}
public static String getFileContent(File f) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
StringBuffer sa = new StringBuffer();
while ((line = br.readLine()) != null) {
sa.append(line);
sa.append("\n");
}
br.close();
return sa.toString();
}
我刚刚将方法分开,以避免在同一代码块中读取文件两次。我希望它可以帮助您,或者至少帮助您满足您的要求。最好的问候。