开发者

How to append to the end of a file in java?

...
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:

开发者_StackOverflow
after 1 input) text1

after 2 input) text1

               text2

and so on...

what should i change in the code? thanks!


java.io.PrintWriter pw = new PrintWriter(new FileWriter(fail, true));

This should do it. Use that over the existing pw line.

edit: And as explained in the comments, this is causing the following things to happen:

  1. 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.

  2. PrintWriter is using this FileWriter (as opposed to creating its own with the file you pass it.)

(A lot of editing going on here. I was uncertain about the question a few times.)


I suggest you use the append flag in the FileWriter constructor.

You also might line to add a newline between each write ;)


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 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().

raf.seek(raf.length());


Instead of using BufferedWriter, use

PrintWriter out = new PrintWriter(kirjutamine);
out.print(t);
out.close();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜