2012-04-14 44 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

什麼問題? – 2012-04-14 19:22:19

+0

什麼是錯誤? – Spoike 2012-04-14 19:28:47

+0

要創建臨時文件,您應該使用File.createTempFile(字符串前綴,字符串後綴,文件目錄)。沒有必要在每一行書寫行後都調用'pw.flush();'。通常在close()之前調用它就足夠了。你應該確保你的流被關閉,把關閉放到finally塊中,否則你可能無法刪除或刪除文件。例如'try {...} ffinally {close(pw); close(br);}'其中close是靜態方法,比如'static void close(Reader r){if(r!= null)try {r.close(); } catch(Exception e){// log}}' – andih 2012-04-14 19:33:43

回答

1

此代碼片段中沒有任何內容會導致文件未被刪除的直接原因。問題更深入 - 權限,通過其他進程打開,通常的東西。檢查所有。當然,刪除失敗後重命名失敗的原因很明顯,所以目前你只有一個你知道的問題。

1

你在Windows上嗎?在Windows上,如果任何進程在文件上具有文件句柄,則取消鏈接並重命名失敗(與UNIX不同)。我甚至注意到,有時候你需要讓操作系統在寫文件和刪除Java文件I/O時進行刪除。 renameTo and delete的文檔給出了一些有限的見解。

爲了簡化您的問題並更好地進行調試,只需創建文件而不是寫入文件 - 使用File.createNewFile()。

可能你有和Cannot delete file Java一樣的問題。