如何在Java中写入txt文件中的特定行号

我目前正在为学校编写项目,该项目要求我读写txt文件.我可以正确读取它们,但只能在最后从附加的FileWriter写入它们.我希望能够通过先删除行上的数据然后写入新数据来覆盖行号上的txt文件中的内容.我试图使用这种方法…

public void overWriteFile(String dataType, String newData) throws IOException
{
    ReadFile file = new ReadFile(path);
    RandomAccessFile ra = new RandomAccessFile(path, "rw");
    int line = file.lineNumber(path, dataType);
    ra.seek(line);
    ra.writeUTF(dataType.toUpperCase() + ":" + newData);
}

但我相信seek方法的移动方向是字节而不是行号.谁能帮忙.提前致谢 :)

附: file.lineNumber方法返回旧数据所在的确切行,因此我已经有需要写入的行号.

编辑:发现了答案!谢谢大家:)如果有人感兴趣,我将在下面发布解决方案

public void overWriteFile(String dataType, String newData, Team team, int dataOrder) throws IOException
{
    try
    {
        ReadFile fileRead = new ReadFile(path);
        String data = "";
        if(path == "res/metadata.txt")
        {
            data = fileRead.getMetaData(dataType);
        }
        else if(path == "res/squads.txt")
        {
            data = fileRead.getSquadData(dataType, dataOrder);
        }
        else if(path == "res/users.txt")
        {
            data = fileRead.getUsernameData(dataType, dataOrder);
        }
        else if(path == ("res/playerdata/" + team.teamname + ".txt"))
        {
            //data = fileRead.getPlayerData(dataType, team.teamname, dataOrder);
        }
        BufferedReader file = new BufferedReader(new FileReader(path));
        String line;
        String input = "";
        while((line = file.readLine()) != null)
        {
            input += line + '\n';
        }
        input = input.replace(dataType.toUpperCase() + ":" + data, dataType.toUpperCase() + ":" + newData);
        FileOutputStream out = new FileOutputStream(path);
        out.write(input.getBytes());
    }
    catch(Exception e)
    {
        System.out.println("Error overwriting file: " + path);
        e.printStackTrace();
    }
}

解决方法:

一种快速而肮脏的解决方案是使用Files.readAllLines和Files.write方法读取所有行,更改要更改的行,然后覆盖整个文件:

List<String> lines = Files.readAllLines(file.toPath());
lines.set(line, dataType.toUpperCase() + ":" + newData);
Files.write(file.toPath(), lines); // You can add a charset and other options too

当然,如果文件很大,那不是一个好主意.有关在这种情况下如何逐行复制文件的一些想法,请参见this answer.

但是,不管如何执行,如果要更改行的字节长度,都将需要重写整个文件(AFAIK). RandomAcessFile允许您在文件中移动并覆盖数据,但不能插入新字节或删除现有字节,因此文件的长度(以字节为单位)将保持不变.

上一篇:NIO学习(十二):Java NIO的MappedByteBuffer的简单使用


下一篇:java – 如何覆盖文件中的某些字节?