How to add a file to the end 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 to a file, then it will go to the first line. But if you run the program again, it writes new text on top of the previous text (on the first line). I want to do: if I insert something, then it goes to the next line. For instance:

after 1 input) text1

after 2 input) text1

               text2

etc.

What should I change in the code? thank!

+3
source share
4 answers
java.io.PrintWriter pw = new PrintWriter(new FileWriter(fail, true));

That should do it. Use this over the existing pw line.

edit: And as explained in the comments, this leads to the following things:

  • A FileWriter is created, with the optional 'append' flag set to true. This causes FileWriter not to overwrite the file, but to open it to add and move the pointer to the end of the file.

  • PrintWriter FileWriter ( , .)

( . .)

+6

append FileWriter.

;)

+3

why don't you use RandomAccessFile? In RandomAccessFileread / write operations can be performed at any position. The file pointer can be moved anywhere by the method seek(). You must specify the file open mode when 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 need to use the seek () function.

raf.seek(raf.length());
+2
source

Instead of using BufferedWriteruse

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

All Articles