2

我希望能够更新文本文件上的某一行。但是我收到无法删除文件的错误,为什么会出现此错误?

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();
        }
    }
}​
4

4 回答 4

2

你应该调查一下RandomAccessFile

这将让您在文件中找到您想要的位置,并且只更新您想要更新的部分。

于 2010-10-07T03:10:30.417 回答
2

该程序对我有用。也许您遇到了环境问题。

于 2010-10-07T03:18:39.953 回答
0

您可以创建一个新实例(关闭旧实例),new然后使用它进行删除。
同样的文件删除问题 在这里

于 2010-10-07T03:28:30.890 回答
0

正如贾斯汀在上面指出的,如果你想修改部分文件,你应该使用 RandomAccessFile 类型的 api。您尝试使用的方法有很多潜在的问题。

  • 它需要另外创建一个 tmp 文件。可能无法针对大文件进行扩展(不过,我不知道您的问题域)
  • 尝试处理文件也可能导致一些潜在的异常,并且需要大量的错误处理。
于 2010-10-07T03:19:52.783 回答