Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrintWriter to print on next line

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

...

like image 705
Acitropy Avatar asked Mar 13 '13 18:03

Acitropy


People also ask

How do I print a new line PrintWriter?

The recommended way is to add the new line is using println() method of PrintWriter class. println() method internally adds the new line character to the contents.

How do I print from a PrintWriter?

PrintWriter output = new PrintWriter("output. txt"); To print the formatted text to the file, we have used the printf() method. Here when we run the program, the output.

What does PrintWriter Println do?

The println(String) method of PrintWriter Class in Java is used to print the specified String on the stream and then break the line. This String is taken as a parameter. Parameters: This method accepts a mandatory parameter string which is the String to be printed in the Stream.

Is PrintWriter faster than system out Println?

PrintWriter class is the implementation of Writer class. By using PrintWriter than using System. out. println is preferred when we have to print a lot of items as PrintWriter is faster than the other to print data to the console.


2 Answers

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

writer.println(RS.getString(1));
like image 148
rgettman Avatar answered Oct 27 '22 00:10

rgettman


You can use PrintWriter#println() method instead.

From API:

Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').

Also this should work as well.

writer.write(RS.getString(1)+ System.getProperty("line.separator"));
like image 26
PermGenError Avatar answered Oct 26 '22 23:10

PermGenError