ZetCode

Java PrintWriter 类

最后修改时间:2025 年 4 月 16 日

java.io.PrintWriter 类为字符流提供格式化输出功能。 它实现了 PrintStream 中的所有 print 方法,但不抛出 I/O 异常。 PrintWriter 可以包装各种输出目标。

PrintWriter 支持在调用 println 方法时自动刷新。 它使用适当的区域设置约定将原始值转换为字符串。 与 PrintStream 不同,PrintWriter 使用适当的字符编码进行文本输出。

PrintWriter 类概述

PrintWriter 扩展了 Writer 并提供了格式化的打印功能。 主要方法包括各种 print 和 println 方法、格式化支持和流控制。 它自动处理字符转换和缓冲。

public class PrintWriter extends Writer {
    public PrintWriter(Writer out);
    public PrintWriter(Writer out, boolean autoFlush);
    public PrintWriter(OutputStream out);
    public PrintWriter(OutputStream out, boolean autoFlush);
    public PrintWriter(String fileName) throws FileNotFoundException;
    public PrintWriter(File file) throws FileNotFoundException;
    
    public void print(boolean b);
    public void print(char c);
    public void print(int i);
    public void print(long l);
    public void print(float f);
    public void print(double d);
    public void print(char[] s);
    public void print(String s);
    public void print(Object obj);
    
    public void println();
    public void println(boolean x);
    // Other println methods...
    
    public PrintWriter printf(String format, Object... args);
    public PrintWriter format(String format, Object... args);
    
    public void flush();
    public void close();
    public boolean checkError();
}

上面的代码显示了 PrintWriter 提供的关键方法。 这些方法允许各种数据类型的格式化输出。 该类支持自动刷新和通过 checkError() 进行错误检查。

创建 PrintWriter

可以使用各种输出目标创建 PrintWriter,包括文件、输出流和其他 writer。 您可以指定自动刷新行为。 构造函数会为文本输出适当地处理字符编码。

Main.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class Main {

    public static void main(String[] args) {
        try {
            // Create with file name
            PrintWriter writer1 = new PrintWriter("output1.txt");
            
            // Create with File object
            PrintWriter writer2 = new PrintWriter(new File("output2.txt"));
            
            // Create with OutputStream
            PrintWriter writer3 = new PrintWriter(
                new FileOutputStream("output3.txt"));
            
            // Create with auto-flush
            PrintWriter writer4 = new PrintWriter(
                new FileOutputStream("output4.txt"), true);
            
            System.out.println("Four PrintWriters created successfully");
            
            writer1.close();
            writer2.close();
            writer3.close();
            writer4.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

此示例演示了创建 PrintWriter 实例的不同方法。 前两个直接为文件创建 writer。 第三个包装一个 OutputStream。 第四个启用 println 调用时的自动刷新。 完成后始终关闭 writer。

使用 PrintWriter 写入文本

PrintWriter 为所有原始类型和对象提供 print 和 println 方法。 这些方法使用 toString 将值转换为字符串。 println 变体在输出后添加行终止符。

Main.java
import java.io.PrintWriter;

public class Main {

    public static void main(String[] args) {
        try (PrintWriter writer = new PrintWriter("output.txt")) {
            
            // Print various data types
            writer.print(true);
            writer.print(' ');
            writer.print(42);
            writer.print(' ');
            writer.print(3.14159);
            writer.println();
            
            writer.println("This is a string");
            writer.println(new Object());
            
            System.out.println("Data written to file");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

此示例显示了使用 PrintWriter 的基本打印操作。 print 方法写入数据,没有行终止符。 println 方法添加适当的行尾。 try-with-resources 确保正确的 writer 关闭。 所有值都转换为字符串。

使用 printf 进行格式化输出

PrintWriter 通过 printf 和 format 方法支持格式化输出。 这些方法使用类似于 C 的 printf 的格式字符串。 格式说明符控制值的转换和显示方式。

Main.java
import java.io.PrintWriter;
import java.util.Date;

public class Main {

    public static void main(String[] args) {
        try (PrintWriter writer = new PrintWriter("formatted.txt")) {
            
            String name = "John Doe";
            int age = 35;
            double salary = 45250.75;
            Date now = new Date();
            
            writer.printf("Name: %s, Age: %d\n", name, age);
            writer.printf("Salary: %,.2f\n", salary);
            writer.printf("Current date/time: %tF %tT\n", now, now);
            writer.printf("Hex value: %x, Octal value: %o\n", 255, 255);
            
            System.out.println("Formatted data written to file");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

此示例演示了使用 PrintWriter 的格式化输出。 %s、%d 和 %f 说明符处理字符串、整数和浮点数。 %tF 和 %tT 格式化日期。 数字格式包括千位分隔符和小数位数。 格式字符串可以包含文字文本和特殊字符。

使用 PrintWriter 进行错误处理

与大多数 I/O 类不同,PrintWriter 方法不会抛出 IOException。 相反,错误在内部跟踪,可以使用 checkError 进行检查。 这使得代码更简洁,但需要显式的错误检查。

Main.java
import java.io.PrintWriter;

public class Main {

    public static void main(String[] args) {
        PrintWriter writer = new PrintWriter(System.out);
        
        // Write some data
        writer.println("First line");
        writer.println(1 / 0);  // ArithmeticException but not caught
        
        // Check for errors
        if (writer.checkError()) {
            System.out.println("An error occurred during writing");
        }
        
        writer.close();
    }
}

此示例显示了 PrintWriter 的错误处理方法。 除以零通常会抛出异常,但 PrintWriter 会抑制它。 必须调用 checkError 方法来检测问题。 此行为与大多数 Java I/O 类不同。

自动刷新行为

PrintWriter 可以配置为在调用 println 时自动刷新。 这确保输出在行尾之后立即写入。 常规 print 调用不会触发自动刷新。

Main.java
import java.io.PrintWriter;

public class Main {

    public static void main(String[] args) {
        // Without auto-flush
        PrintWriter writer1 = new PrintWriter(System.out);
        writer1.print("This won't appear immediately");
        // Need manual flush
        writer1.flush();
        
        // With auto-flush
        PrintWriter writer2 = new PrintWriter(System.out, true);
        writer2.println("This appears immediately due to auto-flush");
        
        writer1.close();
        writer2.close();
    }
}

此示例比较了自动刷新和手动刷新行为。 第一个 writer 需要显式的 flush 调用。 第二个 writer 在 println 上自动刷新。 自动刷新对于需要立即显示的交互式输出很有用。 手动刷新提供对 I/O 操作的更多控制。

写入多个目标

PrintWriter 可以写入各种输出目标,包括系统流、文件和网络连接。 相同的打印方法在所有目标上一致地工作。 这提供了灵活的输出能力。

Main.java
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

public class Main {

    public static void main(String[] args) {
        // Write to standard output
        PrintWriter consoleWriter = new PrintWriter(System.out);
        consoleWriter.println("Writing to console");
        consoleWriter.flush();
        
        // Write to string buffer
        StringWriter stringWriter = new StringWriter();
        PrintWriter stringPrinter = new PrintWriter(stringWriter);
        stringPrinter.println("Writing to string buffer");
        stringPrinter.close();
        System.out.println("String content: " + stringWriter.toString());
        
        // Write to byte array
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        PrintWriter byteWriter = new PrintWriter(byteStream);
        byteWriter.println("Writing to byte array");
        byteWriter.close();
        System.out.println("Byte content: " + byteStream.toString());
        
        consoleWriter.close();
    }
}

此示例演示了具有不同输出目标的 PrintWriter。 第一个写入标准输出。 第二个捕获字符串中的输出。 第三个写入字节数组。 所有都使用相同的打印方法。 这显示了 PrintWriter 在各种输出类型中的多功能性。

来源

Java PrintWriter 类文档

在本文中,我们介绍了 Java PrintWriter 类的基本方法和功能。 了解这些概念对于在 Java 应用程序中使用格式化文本输出至关重要。

作者

我的名字是 Jan Bodnar,我是一位敬业的程序员,在该领域拥有多年的经验。 我于 2007 年开始撰写编程文章,此后撰写了 1,400 多篇文章和八本电子书。 凭借超过八年的教学经验,我致力于分享我的知识并帮助他人掌握编程概念。

列出所有Java教程