2010-10-07 115 views
1

我希望能够更新文本文件上的某一行。 但我得到的错误是它不能删除文件,为什么我会得到这个错误?如何在java中更新文本文件的某些部分

public class Main { 
    public static void main(String[] args) { 
     Main rlf = new Main(); 
     rlf.removeLineFromFile("F:\\text.txt", "bbb"); 
    } 

    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() + ".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().equals(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(); 
     } 
    } 
}​ 
+0

你有写访问F驱动器? – 2010-10-07 03:08:22

+0

如果您先关闭文件,您可以删除该文件吗? – 2010-10-07 03:10:38

+0

哪一行发生异常? – jjnguy 2010-10-07 03:12:56

回答

2

该程序适合我。也许你有一个环境问题。

+0

我需要把它放在同一个目录下, – user225269 2010-10-07 03:27:17

+0

为什么要投票?正如所写的,该程序适用于我。 @ user225269我不这么认为。 – 2010-10-07 03:31:58

2

你应该看看RandomAccessFile

这将让你寻找到你想要的文件的地方,只更新你想要更新的部分。

+0

这是你想用的方法 – Sands 2010-10-07 03:16:08

0

正如Justin在上面指出的那样,如果您想修改文件的某些部分,您应该使用RandomAccessFile类的api。您尝试使用的方法存在很多潜在问题。

  • 它需要另外创建一个tmp文件。虽然可能无法扩展大型文件(但我不知道您的问题域)
  • 尝试打乱文件也会导致一些潜在的异常,并且需要大量的错误处理。
0

您可以通过new创建一个新实例(关闭旧的),然后使用它删除。
相同的文件删除问题here

相关问题