2012-06-28 263 views
0

我正在嘗試從文件中刪除不以特定字符串開頭的行。 想法是將所需的行復制到臨時文件,刪除原始文件並將臨時文件重命名爲原始文件。無法重命名文件

我的問題是我無法重命名一個文件!

tempFile.renameTo(new File(file)) 

tempFile.renameTo(inputFile) 

不起作用。

誰能告訴我發生了什麼問題嗎?下面是代碼:

/** 
* The intention is to have a method which would delete (or create 
* a new file) by deleting lines starting with a particular string. * 
*/ 
package com.dr.sort; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.PrintWriter; 

public class RemoveLinesFromFile { 

    public void removeLinesStartsWith(String file, String startsWith, Boolean keepOrigFile) { 
     String line = null; 
     BufferedReader rd = null; 
     PrintWriter wt = null; 
     File tempFile = null; 

     try { 
      // Open input file 
      File inputFile = new File(file); 

      if (!inputFile.isFile()) { 
       System.out.println("ERROR: " + file + " is not a valid file."); 
       return; 
      } 

      // Create temporary file 

      tempFile = new File(file + "_OUTPUT"); 

      //Read input file and Write to tempFile 

      rd = new BufferedReader(new FileReader(inputFile)); 
      wt = new PrintWriter(new FileWriter(tempFile)); 
      while ((line = rd.readLine()) != null) { 
       if (line.substring(0, startsWith.length()).equals(startsWith)) { 
        wt.println(line); 
        wt.flush(); 
       } 

      } 
      rd.close(); 

      if (!keepOrigFile) { 

       inputFile.delete(); 

       if (tempFile.renameTo(new File(file))) { 
        System.out.println("OK"); 
       } else { 
        System.out.println("NOT OK"); 
       } 
      } 

     } 

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

     finally { 
      if (tempFile != null && tempFile.isFile()) { 
       wt.close(); 
      } 
     } 

    } 
} 
+0

你還沒有告訴我們你得到了什麼錯誤,或者你的問題到底是什麼。 –

+0

對不起所有。我的問題是我無法重命名文件。 tempFile.renameTo(新文件(文件))或tempFile.renameTo(inputFile)不起作用。 – dRv

回答

5

我猜你需要關閉的PrintWriter 之前重命名。

+0

謝謝。我錯過了。 – dRv

0
if (line.substring(0, startsWith.length()).equals(startsWith)) 

應該相反,因爲我們不希望包含指定的行。 so:

if (!line.substring(0, startsWith.length()).equals(startsWith))