2012-06-17 170 views
0

我正在編寫一個程序來查找信息,並通過製作臨時文件,刪除原始文件,然後將temp重命名爲原始文件,從文本文件中將其刪除。到目前爲止,我已經完成了編寫程序的工作,並且在使用Windows控制檯進行編譯時工作正常,但是當我嘗試在netbeans中運行相同的代碼時,它無法工作,因爲它無法刪除並重命名原始文件。我正在尋找解決這個問題的方法。重命名和刪除文件

這裏是代碼,當我編譯它使用Windows控制檯,但不是在NetBeans

import java.io.*; 

public class rename { 
public static String x="1123"; 

public void removeLineFromFile(String file, String lineToRemove) { 

try { 

    File inFile = new File(file); 

    if (!inFile.isFile()) { 
    System.out.println("Parameter is not an existing file"); 
    return; 
    } 

    //Construct the new file that will later be renamed to the original filename. 
    File tempFile = new File(inFile.getAbsolutePath() + "2.tmp"); 

    BufferedReader br = new BufferedReader(new FileReader(file)); 
    PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); 

    String line = null; 

    //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().contains(lineToRemove)) { 

     pw.println(line); 
     pw.flush(); 
    } 
    } 
    pw.close(); 
    br.close(); 

    //Delete the original file 
    if (!inFile.delete()) { 
    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(); 
} 
} 

public static void main(String[] args) { 
rename util = new rename(); 
String jj; 
util.removeLineFromFile("File.txt", x); 
} 
} 
+0

什麼錯誤?發佈你的堆棧跟蹤。 –

+0

只是我的自定義錯誤:無法刪除文件 –

+0

您確定該文件未被控制檯應用程序使用嗎?或另一個程序?所有的流都關閉了嗎?因爲它適用於我... –

回答

0

Humn ...關閉brpw,儘量將它們設置爲null並調用System.gc()後,它的工作原理。

參考:I can't delete a file in java

+0

再次說:無法刪除文件! –

0

重命名

public void rename(String old, String newpath) { 
    try { 
     File folder = new File(old); 
     File[] listOfFiles = folder.listFiles(); 

     for (int i = 0; i < listOfFiles.length; i++) { 

      if (listOfFiles[i].isFile()) { 

       File f = new File(old + listOfFiles[i].getName()); 

       f.renameTo(new File(old + "\\" + newpath)); 

       System.out.println(old + "\\" + newpath); 
      } 
     } 

     System.out.println("conversion is done"); 

    } catch (Exception ex) { 
     Logger.getLogger(CVAdd.class.getName()).log(Level.SEVERE, null, ex); 
    } 

} 
相關問題