如何将新的文本行添加到Java中的现有文件? [英] How to add a new line of text to an existing file in Java?
问题描述
我想追加一个新行到现有的文件,而不删除该文件的当前信息。总之,这里是我使用当前时间的方法:
pre $ import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;
编写器输出;
output = new BufferedWriter(new FileWriter(my_file_name)); //每次清除文件
output.append(New Line!);
output.close();
上面这行代码的问题是简单地删除我现有文件的所有内容,然后添加新的行文本。
我想在文件内容末尾附加一些文本,而不会擦除或替换任何内容。
您必须以追加模式打开文件,这可以通过使用 FileWriter(String fileName,boolean append)
构造函数来实现
output = new BufferedWriter(new FileWriter(my_file_name,true));
应该这样做:
I would like to append a new line to an existing file without erasing the current information of that file. In short, here is the methodology that I am using the current time:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;
Writer output;
output = new BufferedWriter(new FileWriter(my_file_name)); //clears file every time
output.append("New Line!");
output.close();
The problem with the above lines is simply they are erasing all the contents of my existing file then adding the new line text.
I want to append some text at the end of the contents of a file without erasing or replacing anything.
you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append)
constructor.
output = new BufferedWriter(new FileWriter(my_file_name, true));
should do the trick
这篇关于如何将新的文本行添加到Java中的现有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!