user721588
user721588

Reputation:

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:

after 1 input) text1

after 2 input) text1

               text2

and so on...

what should i change in the code? thanks!

Upvotes: 5

Views: 15935

Answers (4)

Neha Choudhary
Neha Choudhary

Reputation: 4870

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

Upvotes: 2

Lak Ranasinghe
Lak Ranasinghe

Reputation: 240

Instead of using BufferedWriter, use

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

Upvotes: 1

John Chadwick
John Chadwick

Reputation: 3213

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

Upvotes: 7

Peter Lawrey
Peter Lawrey

Reputation: 533530

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

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

Upvotes: 3

Related Questions