如何在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方法以字节而不是行号移动。谁能帮忙。提前致谢 :)

PS 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();
    }
}
Cyäegha

一种快速而肮脏的解决方案是使用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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章