1

Here is what I am working with basically (example file):

Line 1: 213124
Line 2: 243223
Line 3: 325425
Line 4: 493258
Line 5: 359823

Is there a way to make PrintWriter begin to write to a file with 5 lines shown above, but so that it only writes AFTER line 5? So like I want to use

    PrintWriter log = new PrintWriter("blah.txt");
    log.println("52525")

and I want it to write that to line 6, not overwrite line 1.

EDIT: For anyone with a similar problem, you want to figure out how to append your files. As of my writing this, two people showed how below

  • Depends. If you mean _append_ to an existing file (i.e. start adding data at the end of the file, after all existing lines) then the answer is yes. Open the file in "append" mode. If you mean start writing at line 6 even though the file contains more than 5 lines, this is also yes, but trickier. – Jim Garrison Mar 27 '16 at 06:00
  • Yes! How do I append stuff? I pretty much, for my purposes, just need it to start writing at the end of the file where there are no more lines. –  Mar 27 '16 at 06:01
  • Possible duplicate of http://stackoverflow.com/questions/25714779/how-can-i-write-to-a-specific-line-number-in-a-txt-file-in-java – Rahman Mar 27 '16 at 06:01

2 Answers2

1

To append to an existing file use "append" mode:

FileOutputStream fos = new FileOutputStream(filename,true);
PrintWriter      pw  = new PrintWriter(fos);

The true argument to the FileOutputStream constructor sets append mode.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
0

To append to a file, you need to use the FileWriter(String fileName, boolean append) constructor:

try (PrintWriter log = new PrintWriter(new FileWriter("blah.txt", true))) {
    log.println("52525");
}

If you're going to write a lot of output, then a BufferedWriter may be good, and if you need to specify the character encoding, you need to wrap a FileOutputStream with an OutputStreamWriter. This makes the chain much longer:

try (PrintWriter log = new PrintWriter(
                         new BufferedWriter(
                           new OutputStreamWriter(
                             new FileOutputStream("blah.txt", true),
                             Charset.forName("UTF-8"))))) {
    log.println("52525");
}

The PrintWriter(String fileName) you called is actually shorthand for:

new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileName)))
Andreas
  • 154,647
  • 11
  • 152
  • 247