java 如何附加到java中的文件末尾?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5896133/
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
How to append to the end of a file in java?
提问by Peter Lawrey
...
Scanner scan = new Scanner(System.in);
System.out.println("Input : ");
String t = scan.next();
FileWriter kirjutamine = new FileWriter("...");
BufferedWriter out = new BufferedWriter(writing);
out.write(t)
out.close();
...
if I write sometring into the file, then it goes to the first line. But if run the programm again, it writes the new text over the previous text (into the first line). I want to do: if I insert something, then it goes to the next line. For example:
如果我将 sometring 写入文件,则它会转到第一行。但是,如果再次运行该程序,它会将新文本写入之前的文本(到第一行)。我想做:如果我插入一些东西,那么它会转到下一行。例如:
after 1 input) text1
after 2 input) text1
text2
and so on...
等等...
what should i change in the code? thanks!
我应该在代码中更改什么?谢谢!
回答by John Chadwick
java.io.PrintWriter pw = new PrintWriter(new FileWriter(fail, true));
This should do it. Use that over the existing pw line.
这应该做。在现有的 pw 线上使用它。
edit: And as explained in the comments, this is causing the following things to happen:
编辑:正如评论中所解释的,这会导致以下事情发生:
A FileWriter is being created, with the optional 'append' flag being set to true. This causes FileWriter to not overwrite the file, but open it for append and move the pointer to the end of the file.
PrintWriter is using this FileWriter (as opposed to creating its own with the file you pass it.)
正在创建 FileWriter,可选的 'append' 标志设置为 true。这会导致 FileWriter 不会覆盖文件,而是打开它进行追加并将指针移动到文件末尾。
PrintWriter 正在使用这个 FileWriter(而不是用你传递的文件创建它自己的。)
(A lot of editing going on here. I was uncertain about the question a few times.)
(这里进行了大量编辑。我有几次不确定这个问题。)
回答by Peter Lawrey
I suggest you use the append
flag in the FileWriter constructor.
我建议您append
在 FileWriter 构造函数中使用该标志。
You also might line to add a newline between each write ;)
您也可以在每次写入之间添加换行符;)
回答by Neha Choudhary
why dont you use RandomAccessFile
?
In RandomAccessFile
, read/write operations can be performed at any position.The file pointer can be moved to anyplace by seek()
method. You have to specify file opening mode while using it.
Example:
你为什么不使用RandomAccessFile
?在 中RandomAccessFile
,可以在任意位置进行读/写操作。文件指针可以通过seek()
方法移动到任意位置。使用时必须指定文件打开方式。例子:
RandomAccessFile raf = new RandomAccessFile("anyfile.txt","rw"); // r for read and rw for read and write.
and to take the file pointer to EOF you have to use seek().
并将文件指针指向EOF,您必须使用seek()。
raf.seek(raf.length());
回答by Lakthinda Ranasinghe
Instead of using BufferedWriter
, use
而不是使用BufferedWriter
,使用
PrintWriter out = new PrintWriter(kirjutamine);
out.print(t);
out.close();