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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25714779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:59:54  来源:igfitidea点击:

How can I write to a specific line number in a txt file in Java

javafiletextfile-iorandomaccessfile

提问by Elliot Lewis

I'm currently writing my project for school in which requires me to read and write to txt files. I can read them correctly but I can only write to them at the end from an appended FileWriter. I would like to be able to overwrite things in my txt files on line numbers by first deleting the data on the line and then writing in the new data. I attempted to use this method...

我目前正在为学校编写项目,其中需要我读取和写入 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);
}

but I believe that the seek method moves along in bytes rather than line numbers. Can anyone help. Thanks in advance :)

但我相信 seek 方法以字节而不是行号为单位移动。任何人都可以帮忙。提前致谢 :)

P.S. the file.lineNumber method returns the exact line that the old data was on so I already have the line number that needs to be written to.

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

EDIT: Soloution found! Thanks guys :) I'll post the soloution below if anyone is interested

编辑:找到解决方案!谢谢你们 :) 如果有人感兴趣,我会在下面发布解决方案

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

采纳答案by Cy?egha

A quick and dirty solution would be to use the Files.readAllLinesand Files.writemethods to read all lines, change the one you want to change, and overwrite the whole file:

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

Of course, that's not a good idea if it's a very big file. See this answerfor some ideas on how to copy the file line by line in that case.

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

Regardless of how you do it, though, if you are changing the byte length of the line, you will need to rewrite the whole file (AFAIK). RandomAcessFile allows you to move around the file and overwrite data, but not to insert new bytes or removes existing ones, so the length of the file (in bytes) will stay the same.

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

回答by Alex K

Here is a link to a question just like this with a great answer: I want to open a text file and edit a specific line in java

这是一个像这样的问题的链接,有一个很好的答案: 我想打开一个文本文件并在 java 中编辑特定行

Basically, you can't just edit that line, unless it'll be the exact same length.

基本上,您不能只编辑该行,除非它的长度完全相同。

Instead, you'll want to copy over every line, and then when you reach the line number of the line you want to change, instead of copying over the old line, just put in your new line.

相反,您需要复制每一行,然后当您到达要更改的行的行号时,不要复制旧行,只需放入新行即可。

The link I gave you has a great example on how to do this.

我给你的链接有一个很好的例子来说明如何做到这一点。

I hope this helps...if not, let me know, and I'll elaborate further on the post. Good luck :)

我希望这会有所帮助...如果没有,请告诉我,我将进一步详细说明该帖子。祝你好运 :)