English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Other Java Topics

Java PrintStream Class

In this tutorial, we will learn about the Java PrintStream class and its print() and printf() methods through examples.

The PrintStream class in the java.io package can be used to write output data in a readable form (text) rather than bytes.

It inherits the abstract class OutputStream.

PrintStream Introduction

Unlike other output streams, PrintStream converts raw data (integers, characters) to text format rather than bytes. Then, it writes the formatted data to the output stream.

And, the PrintStream class does not throw any input/Output exception. Instead, we need to use the checkError() method to find any errors in it.

Note: The PrintStream class also has an automatic flushing feature. This means that it will force the output stream to write all data to the target under the following conditions:

  • If the newline character \n is written to the print stream

  • If the println() method is called

  • If a byte array is written to the print stream

Create a PrintStream

To create a PrintStream, we must first import the java.io.PrintStream package. After importing the package, we can create the print stream here.

1.Using other output streams

//Create a FileOutputStream
FileOutputStream file = new FileOutputStream(String file);
//Create a PrintStream
PrintStream output = new PrintStream(file, autoFlush);

);

  • We have created a print stream that writes formatted data to the file represented by FileOutputStream

  • autoFlush is an optional boolean parameter that specifies whether to perform automatic flushing

2.Using the filename

 //Create a PrintStream
PrintStream output = new PrintStream(String file, boolean autoFlush);

);

  • We have created a print stream that writes formatted data to the specified file

  • autoFlush is an optional boolean parameter that specifies whether to perform automatic flushing

NoteIn these cases, PrintStream uses some default character encodings to write data to the file. However, we can also specify the character encoding(UTF8or UTF16)。

//Create a PrintStream using a character encoding
PrintStream output = new PrintStream(String file, boolean autoFlush, Charset cs);

在这里,我们使用Charset该类来指定字符编码。

Here, we use the Charset class to specify the character encoding.

Methods of PrintStream

The PrintStream class provides various methods that allow us to print the output of data.

  • The print() method - print()

  • Print the specified data to the output stream - println()

Print the data as well as the newline character to the output stream

class Main {
    public static void main(String[] args) {
        Example
        Note this line,
    }
}

String data = "Hello World.";

Output result

Hello World.

In the above example, we have not yet created a print stream. However, we can use the print() method of the PrintStream class.

You may wonder how this is possible. Well, let me explain what happened here.

Note this line,

);

  • System.out.print(data);/System is responsible for executing standard input

  • The final class for output operations

out is a class variable of the PrintStream type declared in the System class

Now, since out is of the PrintStream type, we can use it to call all methods of the PrintStream class.

import java.io.PrintStream;
class Main {
    public static void main(String[] args) {
        Example: The print() method of the PrintStream class
        try {
            PrintStream output = new PrintStream("output.txt");
            String data = "This is a text inside the file.";
            output.close();
        }
        catch(Exception e) {
            e.getStackTrace();
        }
    }
}

output.print(data);output.txtIn the above example, we created a print stream named output. The print stream is associated with

PrintStream output = new PrintStream("output.txt");

File link.

Here, when we run the program,output.txtThe file will be filled with the following content.

To print data to a file, we use the print() method.

This is a text inside the file.

the printf() method2the printf() method can be used to print formatted strings. It includes

parameters: the formatted string and the parameters. For example, 25printf("I %d years old",

);

  • here, - I am %d years old

  • is a formatted string

  • 25%d is the integer data in the formatted string

is the parameter

Therefore, the formatted string includes text and data. Moreover, the parameters replace the data in the formatted string.%d replace it with 25.

Example: Using the printf() method of PrintStream

import java.io.PrintStream;
class Main {
    public static void main(String[] args) {
        try {
            PrintStream output = new PrintStream("output.txt");
            int age = 25;
            output.printf("I am %d years old.", age);
            output.close();
        }
        catch(Exception e) {
            e.getStackTrace();
        }
    }
}

In the above example, we created a print stream named output. The print stream is associated with a fileoutput.txtLink.

PrintStream output = new PrintStream("output.txt");

To print formatted text to a file, we use the printf() method.

Here, when we run the program,output.txtThe file will be filled with the following content.

I am 25 years old.

Other Methods of PrintStream

MethodContent Description
close()Close the print stream
checkError()Check if there is an error in the stream and return a boolean result
append()Attach specified data to the stream