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
...
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.
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.
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.
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.
You should use println
to print a newline character after each line:
writer.println(RS.getString(1));
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With