首先,我是 Java 新手。我给自己设定了一个小项目,但我目前陷入困境。我正在尝试写入一个已经存在的文件,但它只是覆盖它。我正在尝试替换包含“maxBooks”的行。
这是我使用的代码:
FileWriter writeFile = new FileWriter(fileLocation);
BufferedReader readLines = new BufferedReader(new FileReader(fileLocation));
BufferedWriter writeLines = new BufferedWriter(writeFile);
System.out.println("\n-----File Begin-----");
while((finalLines = readLines.readLine()) != null){
if(finalLines.contains("maxBooks")){
writeLines.newLine();
writeLines.write(finalLines);
System.out.println("This is the if statement");
System.out.println(finalLines);
} else {
fileLines.add(new String(finalLines));
System.out.println("This is the else statement");
System.out.println(finalLines);
}
}
System.out.println("------File End------");
请记住,我忽略了尝试和捕捉。请让我知道如何编辑文本文件。如果您需要更多信息,请告诉我
谢谢 :)
编辑
对不起,我应该澄清一下。我只是想编辑测试文件中的 1 行,而不是整个文本文件。
最终代码:
FileWriter writeFile = new FileWriter(fileLocation + ".tmp", true);
BufferedWriter writeLines = new BufferedWriter(writeFile);
BufferedReader readLines = new BufferedReader(new FileReader(fileLocation));
System.out.println("\n-----File Begin-----");
while((finalLines = readLines.readLine()) != null){
if(finalLines.contains("maxBooks")){
writeLines.write("maxBooks = " + maxBooks);
writeLines.newLine();
System.out.println("This is the if statement");
System.out.println(finalLines);
} else {
fileLines.add(new String(finalLines));
System.out.println("This is the else statement");
writeLines.write(finalLines);
writeLines.newLine();
}
}
System.out.println("------File End------");
file2.renameTo(file);
writeLines.close();