2017-04-08 8 views
0

를 사용하여 텍스트 파일에서 선으로 줄을 삭제 그 2 행을 하나씩 읽고 싶습니다. 성공적으로 나는 그 두 줄을 읽었지 만 나는 그것들을 삭제할 때 실패한다. 이것은 내 코드입니다.어떻게 읽고 나는 2 선</p> <ul> <li>안녕하세요을 좋아하는 1</li> <li>안녕하세요 2.</li> </ul> <p>I이 포함 된 텍스트 파일을 자바

@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; 
} 

이제 내 tempFile에서 해당 줄을 삭제하지만 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

문제가 여전히 buttonLineDeleteAction 방법에 의해 잠겨 있기 때문에 사용자가 파일의 내용을 읽는 중간에 당신이 close 파일 판독기 개체를하지 않았다 당신이 (당신의 removeLineFromFile의 첫 번째 파일을 삭제할 수 있다는 것입니다).

(1) 필요한 모든 라인을 찾아 목록으로 그들을 수집하고 파일

(2에게) 닫습니다 새 파일을 만듭니다

그래서, 당신은 아래의 단계를 수행 할 필요가 그리고 목록에서 내용을 작성하고 파일을 닫습니다

(3) 기존 파일을 삭제 이제

(4) 새로운 파일 이름을 바꾸고 새로운 파이를 닫습니다 le