PrintWriter to print on next line

Acitropy picture Acitropy · Mar 13, 2013 · Viewed 40.2k times · Source

I have the following code to print a string(from a ResultSet) to a text file:

PrintWriter writer = new PrintWriter(new FileOutputStream(file, false));
while(RS.next()) {
    writer.write(RS.getString(1)+"\n");
}

I put a "\n" in the write statement in hopes that it will print each row on a different line, but it failed. The txt file currently prints out like so, with row# being a different row in the ResultSet:

row1row2row3row4row5

I want it to print out like:

row1

row2

row3

row4

row5

...

Answer

rgettman picture rgettman · Mar 13, 2013

You should use println to print a newline character after each line:

writer.println(RS.getString(1));