Java 将文本添加到文件中的特定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37276996/
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-11-03 02:22:25  来源:igfitidea点击:

Java add text to a specific line in a file

javafile

提问by user3718160

I would like to know if it's possible to add a line in a File with Java.

我想知道是否可以使用 Java 在文件中添加一行。

For example myFile :

例如 myFile :

1: line 1
2: line 2
3: line 3
4: line 4

I would like to add a line fox example in the third line so it would look like this

我想在第三行中添加一个 line fox 示例,因此它看起来像这样

1: line 1
2: line 2
3: new line
4: line 3
5: line 4

I found out how to add text in an empty file or at the end of the file but i don't know how to do it in the middle of the text without erasing the line.

我发现了如何在空文件或文件末尾添加文本,但我不知道如何在不擦除行的情况下在文本中间添加文本。

Is the another way than to cut the first file in 2 parts and then create a file add the first part the new line then the second part because that feels a bit extreme ?

除了将第一个文件分成 2 部分然后创建一个文件之外,还有另一种方法是将第一部分添加到新行然后添加第二部分,因为这感觉有点极端?

Thank you

谢谢

回答by M. Suurland

In Java 7+ you can use the Filesand Pathclass as following:

在 Java 7+ 中,您可以使用FilesandPath类,如下所示:

List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);

To give an example:

举个例子:

Path path = Paths.get("C:\Users\foo\Downloads\test.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

int position = lines.size() / 2;
String extraLine = "This is an extraline";  

lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);

回答by Daniel Gutierrez

You may read your file into an ArrayList, you can add elements in any position and manipulate all elements and its data, then you can write it again into file.

您可以将您的文件读入一个ArrayList,您可以在任何位置添加元素并操作所有元素及其数据,然后您可以再次将其写入文件。

PD: you can not add a line directly to the file, you just can read and write/append data to it, you must manipulte de data in memory and then write it again.

PD:你不能直接在文件中添加一行,你只能读取和写入/追加数据,你必须在内存中操作数据,然后再次写入。

let me know if this is useful for you

如果这对您有用,请告诉我