try {
File inFile = new File("books.txt");
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 + "temp.txt");
BufferedReader br = new BufferedReader(new FileReader("books.txt"));
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) {
String lineToRemove;
lineToRemove = JOptionPane.showInputDialog("Enter line to remove");
if (!line.trim().contains(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();
}
}
我正在尝试创建一个方法,如果我输入该行中包含的单词,将删除.txt文件中的一行代码。我的问题是,当我运行它时,测试说它无法删除文件。代码有问题吗?我的代码也用#分隔,如果这可能会增加问题。示例输出将是: 巨人#詹姆斯#1993
答案 0 :(得分:1)
我测试了你的代码并进行了微小的修改(@Andreas在写这篇文章的时候注意到了它)并且按预期工作了
(function(){}()