PrintWriter

Java PrintWriter Example

In this example, we are going to look at the PrintWriter class in Java. We will create a printwriter java example and we will print some common data types to the standard output as well as to a file using PrintWriter class.

1. What is the Java PrintWriter class

Java provides the PrintWriter class to print formatted and human-readable data in a stream. This class implements all the print methods found in PrintStream. The text-output stream can be either OutputStream or Writer. More specifically it doesn’t contain methods for printing the primitive types (for instance int, long etc) as byte values, but as text-format representation.

2. PrintWriter Constructor

We will look at the various ways in PrintWriter class can be instantiated

2.1 PrintWriter (File file)

PrintWriter uses an instance of BufferedWriter to write to the final destination. Here, the file handle is passed to the FileOutputstream class to write to the destination. Data is stored in a buffer before writing to optimize the I/O. autoFlush is set to default value of false and only written when manually flushed or when handle exits.

PrintWriter printWriter = new PrintWriter(new File("1.txt"));

2.2 PrintWriter (File file, String csn)

This is a slight variant of the previous constructor which takes in additionally the character encoding to be used while writing to the file. This charset is passed to the OutputStream class which handles writing the file in specified encoding.

PrintWriter printWriter = new PrintWriter(new File("1.txt"),"UTF-8");

In the above example, we specify UTF-8 as the encoding.

2.3 PrintWriter (OutputStream out)

printwriter java

Instead of using a file or file handle, we can arbitrarily pass any instance of Outputstream which will be used by the PrintWriter to write output. autoFlush is set to default value of false and only written when manually flushed or when handle exits.

PrintWriter printWriter = new PrintWriter(new FileOutputStream(new File("jcg.txt")));

2.4 PrintWriter (OutputStream out, boolean autoFlush)

This is a variant of the previous constructor with autoFlush property as input.

PrintWriter printWriter = new PrintWriter(new FileOutputStream(new File("jcg.txt")), true);

2.5 PrintWriter (String fileName)

PrintWriter uses an instance of BufferedWriter to write to the final destination. Here, the filename is passed to the FileOutputstream class which creates the corresponding file handle for the file name passed. autoFlush is set to default value of false and only written when manually flushed or when handle exits.

PrintWriter printWriter = new PrintWriter("jcg.txt");

2.6 PrintWriter (String fileName, String csn)

This is a slight variant of the previous constructor which takes in additionally the character encoding to be used while writing to the file.

PrintWriter printWriter = new PrintWriter("jcg.txt","UTF-8");

2.7 PrintWriter (Writer out)

This takes an instance of Writer to write to the final destination. This can take BufferedWriter or FileWriter where PrintWriter will leverage buffering based on the input Writer.

PrintWriter printWriter = new PrintWriter(new FileWriter("jcg.txt"));

2.8 PrintWriter (Writer out, boolean autoFlush)

This is just variant with autoFlush property as input.

PrintWriter printWriter = new PrintWriter(new FileWriter("jcg.txt"),true);

3. PrintWriter Methods

3.1 print

The above method is used to write the value of the following data types

  • char
  • long
  • float
  • int
  • character array
  • double
  • string
  • boolean
  • object

The method uses String.valueOf for most of the data types except for the few mentioned below.

For
boolean, it writes true in case of truth value or false otherwise. It
writes character array and string natively to the destination using
buffered writer. It converts a null value into explicitly null and
writes it to the destination.

printWriter.print("hi");
printWriter.print((Object) null);

For the above code, we get the following result

hinull

3.2 println

This is very similar to print except that after each call, a newline is created in the destination. Running the same example with println as below

printWriter.println("hi");
printWriter.println((Object) null);
hi
nullhello

Here, the null appears in second line because a newline was inserted by the previous println. But null and hello appear in the same line.

3.3 append

It is very similar to print except it takes a convenient method to write only part of a string or character sequence.

printWriter.println("hi");
printWriter.print((Object) null);
printWriter.append("hello",0,3);

Here, the substring operation is carried out. i.e. the characters from index 0 till 2 excluding the end position specified(3) are extracted and written to the destination.

hi
nullhel

3.4 printf

This
is used to write text to the destination with the specified format
string. The format string specified adhere to the Java format
specifiers.

  int i = 5;
  double k = 10.0;
printWriter.printf("i = %d and k = %f", i, k);
  • %d is used to indicate an integer to be written while %f specifies a float to be written out.
  • Running this produces the following output
i = 5 and k = 10.000000

This optionally takes a locale parameter to specify the locale under which the string needs to be formatted. This internally uses the format method to write the string.

3.5 write

This is essentially used to write bytes and potentially not a solid use case for our class.

filePrintWriter.write("Write something in a line. i = " + 6);

The above example uses the write method to send the string to the destination.

Write something in a line. i = 6

3.6 close

This method is used to close the underlying streams namely the OutputStream, OutputStreamWriter and BufferedWriter. This ensures that the resources are released and good practice to call explictly close after they are no longer needed.

  printWriter.close();
  printWriter.println("text not written");

The text specified is not written as the close has been called before writing the text.

3.7 checkError

This is used to check errors in the PrintWriter class. PrintWriter never throws any exceptions but sets an internal flag.

  printWriter.close();
  printWriter.println("text not written");
 System.out.println("Error State:" + printWriter.checkError());

Considering the example, we can use checkError to identify the presence of error. The above example would print true to the console.

4. Example of Java PrintWriter

Create a java class with name PrintWriterClass and paste the following code.

PrintWriterDemo.java

package com.jcg.demo;

import java.io.*;
import java.util.Date;


public class PrintWriterDemo {


    final static String filename = "jcgFile.txt";

    public static void main(String[] args) {
        // the standard output as OutputStreamWriter
        PrintWriter printWriter = new PrintWriter(System.out, true);
        printWriter.println("Java Code Geeks");
        int i = 5;
        double k = 10.0;
        printWriter.printf("i = %d and k = %f", i, k);
        // flush the instance pw
        printWriter.flush();

        System.out.println("\n---------------------------------------");

        // write sth in a file (deletes the lines if exist)
        PrintWriter filePrintWriter = null;
        Date date = new Date();
        try {
            filePrintWriter = new PrintWriter(filename);
            i++;
            // write a builtIn object
            filePrintWriter.println(date);
            filePrintWriter.write("Write something in a line. i = " + i);
            System.out.println("Write to the file successfully");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } finally {
            // always close the output stream
            if (filePrintWriter != null) {
                filePrintWriter.close();
            }
        }

        PrintWriter bufferedFileWriter = null;
        Object obj = System.getProperty("line.separator") + "A new object";
        // write in a file in a newline (no deletion of previous writing)
        try {
            FileWriter fl = new FileWriter(filename, true);
            BufferedWriter br = new BufferedWriter(fl);
            bufferedFileWriter = new PrintWriter(br);

            bufferedFileWriter.println(obj);
            // write the string beginning from the 3rd char until the 8th
            bufferedFileWriter.write("!!!JCG Test!!!", 3, 8);
            System.out.println("Add new lines to the file successfully");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // for FileWriter
            e.printStackTrace();
        } finally {
            // no matter what happen, close the output stream
            if (bufferedFileWriter != null) {
                bufferedFileWriter.close();
            }
        }
    }

}

As you can see from the code above, we have different instances of PrintWriter class, in order to show different situations.

Firstly, we create the printWriter instance from the existing System.out OutputStreamWriter. Also, we set the second parameter to true, so the printing methods will flush the output buffer. As you can notice, println() and printf() methods are called and the standard output will convert characters into bytes with the use of the default character encoding. For int and double data types, %d
and %f should be declared in the printf() method. flush() method is used in order to flush the stream.

The second instance – filePrintWriter – represents a PrintWriter with a specified file, in order to write into a specific file. We should declare the full path of the file, which denotes the destination of this writer. It is worth to mention that if the file doesn’t exist, it will be created. Also notice that we should throw FileNotFoundException if the file doesn’t represent an existing writable regular file, as well as SecurityException for write access permissions. In this situation println() method is called again, where it prints the built-in object (Date) and terminates the line. In addition, write() method writes the specified string to the file.

Finally, we create bufferedFileWriter instance and we set BufferedWriter as character-output stream. For the instance of BufferedWriter we should use FileWriter class too by setting the specified file as parameter. In this situation, we can print/write into the file but without deleting the previous lines. As you can notice, println() prints an object that we created. Also, we use write() method with specific parameters in order to write a part of the specified string. Essentially, we declare a string in the first parameter then we set the offset from which the writing is beginning and finally we set the number of writing characters to the last parameter.

It is worth to mention that we should close the stream, so close() method is called into finally block. So, even if an exception is thrown, the stream always closes and any associated system resources are released.

Below you can see the output of the execution.

Output

Java Code Geeks
i = 5 and k = 10.000000
---------------------------------------
Write to the file successfully
Add new lines to the file successfully

Also, you can see what the stream wrote into the file during the execution.

jcgFile.txt

Wed Mar 19 13:25:08 EET 2014
Write something in a line. i = 6
A new object
JCG Test

5. When to Use PrintWriter

PrintWriter should be used to write formatted representations rather than writing the raw bytes. The fundamental difference is that PrintWriter uses an instance of Writer which is used to write characters than the raw bytes. PrintWriter is similar to PrintStream very much implementing the interfaces of Appendable, Flushable and Closeable. PrintStream uses an OutputStream and delivers to the destination the bytes even if a String is passed. Since much of the real-world applications typically uses string, it would be advisable to use PrintWriter to print data to the output destination. The other need is it wraps internally the BufferedWriter so it would be a good use case when we need to deliver the data to destination periodically than immediately.

6. Download the source file

This was a tutorial about PrintWriter in Java.

Download
Download the source code of this example: Java PrintWriter Example

Last updated on Mar. 31st, 2020

Katerina Zamani

Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button