是否有可能在Java中修改文本文件的某一行,而不会覆盖所有内容

时间:2012-08-08 14:34:11

标签: java file-io

我有一个文本文件。我想在该文件中的某处只修改一行。我不想覆盖文件的其他行(在大文件上速度极慢)。

我没有引用追加模式,我可以在最后添加“行”;而是“编辑”。

3 个答案:

答案 0 :(得分:3)

您可以使用RandomAccessFile执行此操作。您更改了第一行的内容。

您不能做的是插入或删除任何字节,因为这需要您从执行此操作的位置移动所有数据。 (如果这接近文件的末尾,它可能比重写所有内容快得多)

RandomAccessFile很难与char一起使用,因为它设计用于byte

答案 1 :(得分:2)

您的标题说明“某一行” - 您的问题正文表示“第一行”。修改第一行很多更简单,因为您不需要找到该行的起始字节。您可以使用RandomAccessFile覆盖文件的相关块。

但是,新行必须与旧行的大小(以字节为单位)相同。如果新行中的有​​用数据比旧行中的有用数据短,则需要确定如何填充它。如果新行需要更长而不是旧行,则必须创建一个新文件,并相应地复制数据。

通常,文件系统不支持在现有文件中插入或删除。

答案 2 :(得分:1)

你可以这样做(这绝不是最佳代码)。

import java.io.*;

public class Test {
    // provide the file name via the command line
    public static void main(String []args) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader("your_file_name_here")); // used for reading the file
        BufferedWriter bw = new BufferedWriter(new FileWriter("new_file_name_here.txt"));
        String str = br.readLine();
        while (str != null) {
            // modify the line here if you want, otherwise it will written as is.
            // then write it using the BufferedWriter
            bw.write(str, 0, str.length());
            bw.newLine();
            // read the next line
            str = br.readLine();
        }
        br.close();
        bw.close();
    }
}