2014-04-29 6 views
0

다음 코드를 사용자 지정 메서드에 추가했습니다.줄을 제거한 후 temp.txt의 이름을 original.txt로 바꿀 수 없습니다.

File inputFile = new File("F:\\EmployeePunch\\EmployeePunch\\src\\employeepunch\\original.txt"); // Your file 
File tempFile = new File("F:\\EmployeePunch\\EmployeePunch\\src\\employeepunch\\temp.txt");// temp file 
BufferedReader reader = null; 
BufferedWriter writer = null; 
try{ 
reader = new BufferedReader(new FileReader(inputFile)); 
writer = new BufferedWriter(new FileWriter(tempFile)); 

String firstName = chosenEmployee.getFirstName(); 
String lastName = chosenEmployee.getLastName(); 

String currentLine; 

while((currentLine = reader.readLine()) != null) { 

    if(currentLine.contains(firstName) 
     && currentLine.contains(lastName)) continue; 

    writer.write(currentLine); 
} 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
     }finally{ 
      try { 
       inputFile.delete(); 
       writer.close(); 
       boolean successful = tempFile.renameTo(inputFile); 
       System.out.println(successful); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 

     } 

문제는 다음과 같습니다. 프로그램을 실행할 때마다 renameTo이 실패합니다. 하지만 제거 된 것으로 가정 된 줄로 temp.txt가 올바르게 제거됩니다.

renameTo은 항상 false를 반환하나요?

편집 1 : 파일은 Windows의 다른 곳에서는 열 수 없습니다. 그들은 내 IDE의 프로젝트 탐색기에 나열되어 있지만 내 IDE에 의해 열리지 않습니다.

+0

같습니다 BufferedReader'. 따라서 파일은 아직 열려 있습니다. – anonymous

답변

1

renameTo()에 대한 javadoc는 말한다 : 그것은 원자되지 않을 수도

이름 바꾸기 작업이 또 다른 하나 개의 파일 시스템에서 파일을 이동하지 못할 수 있습니다, 그리고 은 성공하지 않을 수 있습니다 경우의 파일 목적지 추상 경로 이름은 이미 존재합니다.

것은 (당신은 "사용"reader은 그래서 아직도 폐쇄되지 않음) 먼저 입력 파일을 삭제하는 모든 파일을 닫으십시오 : 당신이`를 통해 입력 파일을 액세스하는 것처럼

} finally { 
    try { 
     inputFile.delete(); 
     reader.close(); 
     writer.close(); 
     inputFile.delete(); 
     boolean successful = tempFile.renameTo(inputFile); 
     System.out.println(successful); 
    } catch (IOException ex) { 
      ex.printStackTrace(); 
    } 

} 
+0

그 덕분에 해결! – Tukajo