2017-04-08 73 views
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 

請幫助我的人。提前致謝。

回答

0

的問題是,你不能刪除第一個文件在您的removeLineFromFile,因爲它仍然是由您buttonLineDeleteAction方法鎖定(如你在讀取文件內容的過程中,你沒有close文件讀者對象)。

所以,你需要按照下面的步驟:

(1)找出所有需要的行,並將其收集到一個列表和關閉文件

(2)創建一個新的文件從列表寫的內容和關閉文件

(3)刪除舊文件現在

(4)重命名新的文件,並關閉新的網絡連接le