I have the following code
FileWriter F = new FileWriter("out.txt");
PrintWriter H = new PrintWriter(F);
H.print(split[split.length - 2]);
H.print("END");
When I examine the txt however, the last text is NOT 'END', but part of a word in the string. It is "repa"
When I do this
FileWriter F = new FileWriter("out.txt");
PrintWriter H = new PrintWriter(F);
System.out.print(split[split.length - 2]);
The last bit of text I get is the number '49' - this is correct.
It appears that the PrintWriter is not fully writing out the string. However, when I do this
FileWriter F = new FileWriter("out.txt");
PrintWriter H = new PrintWriter(F);
H.print(split[split.length - 2]);
H.println(pdfInText)://Another string
H.print("END");
The 'original' text now actually finishes - what is this?
The print writer is linked with the file output.PrintWriter output = new PrintWriter("output. txt"); To print the formatted text to the file, we have used the printf() method.
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.
Class PrintWriter. Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream . It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
The write(String) method of PrintWriter Class in Java is used to write the specified String on the stream. This String value is taken as a parameter. Parameters: This method accepts a mandatory parameter string which is the String to be written in the Stream. Return Value: This method do not returns any value.
Do you close the PrintWriter
? From its javadoc
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println() methods is invoked, rather than whenever a newline character happens to be output. The println() methods use the platform's own notion of line separator rather than the newline character.
If you do close the PrintWriter
(and not the FileWriter!) try a flush()
after printing, to force that.
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