【问题标题】:how to update certain parts of text file in java如何在java中更新文本文件的某些部分
【发布时间】:2011-04-22 03:48:25
【问题描述】:

我希望能够更新文本文件中的某一行。 但是我得到它无法删除文件的错误,为什么我会得到这个错误?

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

【问题讨论】:

  • 你对F盘有写权限吗?
  • 先关闭文件可以删除吗?
  • 异常发生在哪一行?
  • 是的,我以管理员身份登录。该文件在我运行时已关闭。

标签: java text-files bufferedreader


【解决方案1】:

该程序适合我。也许您遇到了环境问题。

【讨论】:

  • 是否需要放在同一个目录下,
  • 为什么投反对票?所写的程序对我有用。 @user225269 我不这么认为。
【解决方案2】:

你应该看看RandomAccessFile

这会让你在文件中寻找你想要的位置,并且只更新你想要更新的部分。

【讨论】:

  • 这是您想要使用的方法
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多