2012-04-14 2 views
0

Java 프로그래밍에서 파일을 삭제 한 다음 이름을 변경하는 데 도움이 필요합니다. 내 문제는 원래 파일을 삭제할 수 없으며 두 번째 파일의 이름을 바꿀 수 없다는 것입니다. 다음은 스 니펫 코드입니다. 어떤 제안이라도 인정 될 것입니다.Java 프로그래밍에서 파일 삭제 및 이름 바꾸기

import java.awt.event.*; 
import java.io.*; 
import java.util.ArrayList; 
import java.util.Scanner; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.*; 




public void deleteLine(String content) { 
    try { 

     File inFile = new File("football.dat"); 
     if (!inFile.isFile()) { 
      System.out.println("Parameter is not an existing file"); 
      return; 
     } 
     File tempFile = new File(inFile.getAbsolutePath() + "2"); 
     BufferedReader br = new BufferedReader(new FileReader(inFile)); 
     PrintWriter pw = new PrintWriter(new FileWriter(tempFile), true); 

     String linetobeempty = null; 
     while ((linetobeempty = br.readLine()) != null) { 

      if (!linetobeempty.trim().equals(content)) { 
       pw.println(linetobeempty); 
       pw.flush(); System.out.println(linetobeempty); 
      } 
     } 

     pw.close();   
     br.close(); 
     boolean b = inFile.delete(); 

     if (!b) { 
      System.out.println("Could not delete file"); 
      return; 
     } 

     //Rename the new file to the filename the original file had. 
     if (!tempFile.renameTo(inFile)) { 
      System.out.println("Could not rename file"); 
     } 


    } catch (FileNotFoundException ex) { 
     ex.printStackTrace(); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
} 
+0

무엇이 문제입니까? –

+0

무엇이 오류입니까? – Spoike

+0

임시 파일을 만들려면'File.createTempFile (문자열 접두어, 문자열 접미사, 파일 디렉토리)를 사용해야합니다. 모든 p 든 행 다음에'pw.flush();'를 호출 할 필요가 없습니다. 보통'close()'전에 호출하는 것으로 충분합니다. 스트림이 닫히는 지 확인하고 finally 블록에 닫기를 넣어야합니다. 그렇지 않으면 파일을 삭제하거나 제거하지 못할 수 있습니다. 예를 들어'try {...} ffinally {close (pw); close (br);}'close는 정적 static close (Reader r)와 같은 정적 메소드입니다. if (r! = null) try {r.close(); } catch (Exception e) {// log}}' – andih

답변

1

이 코드 스 니펫에는 삭제되지 않는 파일의 직접적인 원인은 없습니다. 문제는 더 깊은 권한 아래 놓여 있으며 다른 프로세스에 의해 열립니다. 모든 것을 확인하십시오. 물론 삭제 실패 후에 이름 바꾸기가 실패하는 이유는 분명하므로 현재 알고있는 문제는 하나뿐입니다.

1

Windows 사용자입니까? Windows에서 UNIX와 달리 파일에 파일 핸들이있는 프로세스의 경우 연결 해제 및 이름 바꾸기가 실패합니다. 심지어 때로는 OS에서 파일 쓰기와 Java에서 파일 I/O 테스트를 할 때 삭제가 필요하다는 사실을 알게되었습니다. renameTo and delete의 의사는 제한된 통찰력을 제공합니다.

문제를 단순화하고 디버깅을 개선하려면 File.createNewFile()을 사용하여 파일을 작성하는 대신 작성하십시오.

가능성있는 문제는 Cannot delete file Java입니다.