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

Ell*_*wis 8 java file-io text file randomaccessfile

我正在写我的学校项目,其中要求我读取和写入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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

编辑:Soloution发现!谢谢大家:)如果有人有兴趣,我会在下面发布soloution

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Cyä*_*gha 8

一个快速而肮脏的解决方案是使用Files.readAllLinesFiles.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
Run Code Online (Sandbox Code Playgroud)

当然,如果它是一个非常大的文件,这不是一个好主意.有关如何在这种情况下逐行复制文件的一些想法,请参阅此答案.

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