如何在Java中更新文本文件的某些部分 [英] how to update certain parts of text file in java
本文介绍了如何在Java中更新文本文件的某些部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够更新文本文件上的特定行。
但出现错误,它无法删除文件,为什么会出现此错误?
I want to be able to update a certain line on a text file. But I get the error that it cannot delete the file, why do I get this error?
public class Main {
public static void main(String[] args) {
Main rlf = new Main();
rlf.removeLineFromFile("F:\\text.txt", "bbb");
}
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
推荐答案
该程序对我有用。也许您遇到了环境问题。
The program works for me. Perhaps you are having an environmental issue.
这篇关于如何在Java中更新文本文件的某些部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文