This article is a quick introduction to the Printstream Java class available as part of Java ecosystem.
Stream refers to data essentially bytes at lowest level. To read and process data from a source, the data needs to be saved. Outputstream is the means to save the data to a sink.
Outputstream is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of
OutputStream must always provide at least a method that writes one byte of output.
PrintStream is an implementation of
Outputstream. It adds provides the ability to print representations of various data values conveniently.
PrintStream sets an error flag instead of throwing
IOException in case of exception scenarios and flushes automatically to the sink.
should be used to write characters than bytes. It uses platform’s default character encoding to convert the characters into bytes.
In this section, we will look at some ways of initializing
Printstream. We can directly pass a filename to be written.
PrintStream printStream = new PrintStream("test.txt");
Printstream uses an instance of
Outputstream 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.
FileOutputStream fileOutputStream = new FileOutputStream("test.txt"); PrintStream printStream = new PrintStream(fileOutputStream);
The only difference to above is we manually create the
Outputstream and pass to
Printstream. Though, we have passed
FileOutputstream it could be any other. For example
SocketOutputstream in case of writing to a network socket.
In both of the above methods, data is not written to the destination immediately. It is stored in a buffer and only written when manually flushed or when handle exits.
FileOutputStream fileOutputStream = new FileOutputStream("test.txt"); PrintStream printStream = new PrintStream(fileOutputStream,true);
Alternatively, the constructor take a flush argument which flushes to the output stream whenever a byte array is written or newline character is written. The other variant of constructor is one which takes in a character encoding as input.
FileOutputStream fileOutputStream = new FileOutputStream("test.txt"); PrintStream printStream = new PrintStream(fileOutputStream, true, "UTF-8");
Here UTF-8 is specified as the character encoding which needs to be used for writing the file.
The above method is used to write the value of the following data types
- character array
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.
printStream.print("hi"); printStream.print((Object) null);
For the above code, we get the following result
This is very similar to
println as below
printStream.println("hi"); printStream.print((Object) null); printStream.print("hello");
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.
It is very similar to print except it takes a convenient method to write only part of a string or character sequence.
printStream.println("hi"); printStream.print((Object) null); printStream.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.
This is used to write text to the destination with the specified format string. The format string specified adhere to the Java format specifiers.
printStream.printf("%nIt is %d year to %s", 1, "2021");
- We specify %n to insert a newline in the destination.
- %d is used to indicate an integer to be written while %s specifies a string to be written out.
- Running this produces the following output
It is 1 year to 2021
This optionally takes a locale parameter to specify the locale under which the string needs to be formatted.
This is essentially used to write bytes and potentially not a solid use case for our class.
The above printstreams example converts the string representation of bytes to a byte array and uses the write method to deliver to the destination.
This method is used to close the underlying streams namely the
BufferedWriter. This ensures that the resources are released and good practice to call explictly close after they are no longer needed.
printStream.close(); printStream.println("text not written");
The text specified is not written as the close has been called before writing the text.
This is used to check errors in the
PrintStream class. Printstream in java throws any exceptions but sets an internal flag.
printStream.close(); printStream.println("text not written"); System.out.println("Error State:" + printStream.checkError());
Considering the example, we can use
checkError to identify the presence of error. The above example would print true to the console.
We have seen the use of
PrintStream methods and constructors with various examples in this post.
4. Download the Source Code
You can download the full source code of this example here: PrintStream Java Example