0
我有一个包含2线喜欢如何阅读和使用Java
- 的Hello World 1.
- 的Hello World 2.
我的文本文件从文本文件一行删除线想要逐一阅读和删除这2行。成功我读了这两行,但当我删除那些失败。这是我的代码。
@FXML
public void buttonLineDeleteAction(ActionEvent event) throws IOException {
try {
String line = null;
final File fileGpNumber = new File(filePath);
FileReader fileReader = new FileReader(fileGpNumber);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
System.out.println("Line--- " + line);
boolean result = removeLineFromFile(line);
System.out.println("Result---> " + result);
}
} catch (IOException e) {
System.out.println("IOException " + e);
}
}
并删除线路再见这种方法。
private boolean removeLineFromFile(String lineToRemove) {
boolean isDeleted = false;
try {
File inFile = new File(filePath);
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(filePath));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line;
//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();
isDeleted = false;
} else {
isDeleted = true;
}
}
pw.close();
br.close();
//Delete the original file
if (inFile.delete()) {
isDeleted = true;
} else {
isDeleted = false;
System.out.println("Could not delete file.");
}
//Rename the new file to the filename the original file had.
if (tempFile.renameTo(inFile)) {
isDeleted = true;
} else {
System.out.println("Could not rename file.");
isDeleted = false;
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return isDeleted;
}
现在删除我的临时文件,但这些问题在行删除INFILE和重命名文件thetempFile。 这是我的输出
Line--- Hello World 1.
Could not delete file.
Could not rename file.
Result---> false
Line--- Hello World 2.
Could not delete file.
Could not rename file.
Result---> false
请帮助我的人。提前致谢。