Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrintWriter not printing out complete string

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?

like image 621
DreamsOfHummus Avatar asked Dec 10 '12 18:12

DreamsOfHummus


People also ask

How do I print from a PrintWriter?

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.

Is PrintWriter faster than system out Println?

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.

Is PrintWriter an output stream?

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.

What is the method that writes a string using a PrintWriter?

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.


1 Answers

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.

like image 71
Pyranja Avatar answered Sep 19 '22 11:09

Pyranja