Keith Kaplan
Keith Kaplan

Reputation: 109

How to write more than once to text file using PrintWriter

I know how to create a PrintWriter and am able to take strings from my gui and print it to a text file.

I want to be able to take the same program and print to the file adding text to the file instead of replacing everything already in the text file. How would I make it so that when more data is added to the text file, it is printed on a new line every time?

Any examples or resources would be awesome.

Upvotes: 3

Views: 5681

Answers (3)

Balaswamy Vaddeman
Balaswamy Vaddeman

Reputation: 8530

PrintWriter writer=new PrintWriter(new FileWriter(new File("filename"),true));
writer.println("abc");

FileWriter constructor comes with append attribute,if it is true you can append to a file.

check this

Upvotes: 1

Wyzard
Wyzard

Reputation: 34563

Your PrintWriter wraps another writer, which is probably a FileWriter. When you construct that FileWriter, use the constructor that takes both a File object and an "append" flag. If you pass true as the append flag, it'll open the file in append mode, which means that new output will go at the end of the file's existing contents, rather than replacing the existing contents.

Upvotes: 0

vikiiii
vikiiii

Reputation: 9456

    try 
    {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
    out.println("the text");
    out.close();
     } catch (IOException e) {
    }

The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file).

Using a BufferedWriter is recommended for an expensive writer (i.e. a FileWriter), and using a PrintWriter gives you access to println syntax that you're probably used to from System.out.

But the BufferedWriter and PrintWriter wrappers are not strictly necessary.

Upvotes: 7

Related Questions