杰瑞科技汇

java printstream

Of course! Let's dive deep into java.io.PrintStream in Java.

java printstream-图1
(图片来源网络,侵删)

What is a PrintStream?

A PrintStream is an output stream that adds functionality to another output stream, primarily the ability to print representations of various data values (int, String, Object, etc.) in a human-readable format. It is one of the most fundamental and widely used classes in Java for console and file output.

The key characteristics of a PrintStream are:

  1. Automatic Flushing: It can be set to automatically flush its internal buffer. This is extremely useful for console output, where you want to see the message immediately.
  2. No IOException: Unlike most other I/O classes, PrintStream methods do not throw IOException. Instead, they set an internal error flag that can be checked with the checkError() method. This makes it much easier to use for simple tasks, as you don't have to wrap every call in a try-catch block.
  3. Rich Printing Methods: It provides overloaded print() and println() methods for all primitive types (int, double, boolean, etc.) and for Object (which calls its toString() method).
  4. Formatted Output: It includes the printf() and format() methods, which allow for C-style formatted string output.

Key Methods

Here are the most important methods you'll use with PrintStream:

Method Description
print(Object obj) Prints the string representation of the object (using toString()) to the stream. It does not append a new line at the end.
println() Prints a line separator (the platform's default line separator, like \n on Unix or \r\n on Windows).
println(Object obj) Prints the string representation of the object, followed by a line separator. This is the most common method for console output.
printf(String format, Object... args) A powerful method that writes a formatted string to the stream. It uses a format specifier (e.g., %d, %s, %f) to format the arguments.
format(String format, Object... args) Does the exact same thing as printf(). It was added for consistency with the Formatter class.
void flush() Forces the output to be written to the underlying destination, clearing any buffered characters.
boolean checkError() Returns true if an error has occurred on this stream.

Creating a PrintStream

You typically create a PrintStream by wrapping an existing OutputStream.

java printstream-图2
(图片来源网络,侵删)

Standard Output: System.out

This is the most common way you'll use a PrintStream. By default, System.out is a PrintStream that writes to the standard console output.

public class PrintStreamExample {
    public static void main(String[] args) {
        // System.out is a pre-instantiated PrintStream
        System.out.println("Hello, World!"); // println() adds a newline
        System.out.print("This is on the same line. ");
        System.out.println("This is on the next line.");
        int age = 30;
        double price = 19.99;
        System.out.printf("Age: %d, Price: %.2f%n", age, price); // %n is platform-independent newline
    }
}

Creating a Custom PrintStream (e.g., to a File)

You can create a PrintStream to write to a file. It's crucial to wrap it in a try-with-resources block to ensure the stream is automatically closed.

import java.io.FileNotFoundException;
import java.io.PrintStream;
public class FilePrintStreamExample {
    public static void main(String[] args) {
        // Use try-with-resources to automatically close the PrintStream
        try (PrintStream fileOut = new PrintStream("output.txt")) {
            // Redirect standard output to the file
            System.setOut(fileOut);
            System.out.println("This line will be written to output.txt");
            System.out.println("This will be on the second line of the file.");
            // You can still use printf for formatting
            System.out.printf("User: %s, Score: %d%n", "Alice", 95);
        } catch (FileNotFoundException e) {
            System.err.println("Could not find the file to write to.");
            e.printStackTrace();
        }
    }
}

After running this, a file named output.txt will be created with the specified content.


PrintStream vs. PrintWriter

This is a very common point of confusion. They are very similar, but with a key difference:

java printstream-图3
(图片来源网络,侵删)
Feature PrintStream PrintWriter
Superclass FilterOutputStream (works with bytes) Writer (works with characters)
Character Encoding Does not use character encoding. It converts characters to bytes using the platform's default encoding, which can cause issues on different systems. Uses character encoding. You can specify the encoding, making it more reliable for international text.
Error Handling Does not throw IOException. It sets an internal error flag (checkError()). Throws IOException.
Auto-Flush Can be constructed with a boolean flag for auto-flushing. Can be constructed with a boolean flag for auto-flushing.
Primitive Methods Has print()/println() for all primitive types (byte, short, int, long, float, double, char, boolean). Only has print()/println() for char, char[], String, and Object. For other primitives, you must convert them to a String first.

Which one should you use?

  • Use PrintStream for:

    • Writing to the console (System.out, System.err).
    • Writing to binary files where the encoding isn't a primary concern.
    • Situations where you want to avoid IOException for simplicity.
  • Use PrintWriter for:

    • Almost all other text file writing. It is the more robust and correct choice for handling text because it allows you to specify the character encoding (e.g., UTF-8), ensuring your application works consistently across different operating systems.

Advanced: Auto-Flushing

You can create a PrintStream that automatically flushes its buffer after every println() call. This is useful for real-time logging where you don't want messages to be buffered.

import java.io.OutputStream;
import java.io.PrintStream;
public class AutoFlushExample {
    public static void main(String[] args) {
        // true enables auto-flushing after println()
        PrintStream autoFlushOut = new PrintStream(System.out, true);
        System.out.println("This line is from System.out. (May be buffered)");
        autoFlushOut.println("This line is from autoFlushOut. (Will appear immediately)");
        System.out.println("This line is from System.out again. (May be buffered)");
    }
}

You will notice that the message from autoFlushOut appears on the console before the subsequent System.out message, demonstrating the immediate flush.

Summary

PrintStream is a cornerstone of Java's I/O system, providing a simple and powerful way to output text. While PrintWriter is generally the better choice for file writing due to its proper handling of character encodings, PrintStream remains essential for console output (System.out) and scenarios where avoiding IOException is beneficial. Its printf() method is indispensable for creating well-formatted output.

分享:
扫描分享到社交APP
上一篇
下一篇