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
請幫助我的人。提前致謝。