Java IO: PrintWriter

Connect with me:  
  Jenkov.com - News

The PrintWriter class enables you to write formatted data to an underlying Writer. For instance, writing int, long and other primtive data formatted as text, rather than as their byte values.

Here is a simple example:

PrintWriter writer = new PrintWriter(writer);

writer.print(true);
writer.print((int) 123);
writer.print((float) 123.456);

writer.printf(Locale.UK, "Text + data: %1$", 123);    

writer.close();

The PrintWriter class contains the powerful format() and printf() methods (they do exactly the same, but the name "printf" is more familiar to C-programmers). These methods allow you to mix text and data in very advanced ways, using a formatting string. For more information about format() and printf() see the JavaDoc.

The PrintWriter has a wide selection of contructors that enable you to connect it to a File, an OutputStream, or a Writer.

Connect with me:
     
Newsletter - Get all my free tips!