Java--打印流

基本介绍

在整个IO包中,打印流是输出信息做方便的类,主要包含字节打印流(PrintStream)和字符打印流(PrintWriter)。打印流提供了非常方便的打印功能,可以打印任何的数据类型,例如:小数、整数、字符串等等

代码说明

PrintStream 的使用

java 复制代码
import java.io.IOException;
import java.io.PrintStream;

/**
 *  演示 PrintStream(字节打印流)
 */
public class PrintStream_ {
    public static void main(String[] args) throws IOException {
        PrintStream out = System.out;
        // 在默认情况下,PrintStream 输出数据的位置是标准输出,即显示器
        /*
        public void print(String s) {
            if(s == null) {
                s = "null";
            }
            write(s);
        }
         */
        out.print("Hello John !");
        // 因为 print 底层使用的是 write,所以我们可以直接使用 write 来进行打印/输出
        out.write("你好,哈尔滨".getBytes());
        out.close();

        // 我们可以修改打印位置
        // 修改到 D:\hello.txt
        System.setOut(new PrintStream("D:\\hello.txt"));
        /*
                public static void setOut(PrintStream out) {
                    checkIO();
                    setOut0(out);  // native 方法,修改了 out 位置
                }
         */
        System.out.println("人生得意需尽欢");// 这句话会打印到上面的文件中,因为已经修改了打印位置
    }
}

PrintStream 的使用

java 复制代码
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class PrintWriter_ {
    public static void main(String[] args) throws IOException {
        // 默认打印显示器
        // PrintWriter printWriter = new PrintWriter(System.out);
        PrintWriter printWriter = new PrintWriter(new FileWriter("f2.txt"));
        printWriter.println("Hi,北京你好!");  // 打印到指定文件,如上衣语句的文件

        // 记得一定要 close()
        printWriter.close(); // flush + 关闭流
    }
}
相关推荐
Scott9999HH4 小时前
【IIoT流量实战】蒸汽管道阀门全关却仍有流量?用 Python 实现涡街信号 FFT 频谱分析与温压全补偿积算网关,深度拆解靠谱的涡街流量计厂家硬核技术标准
开发语言·python
腻害兔4 小时前
【若依项目-产品经理视角】深度拆解 RuoYi-Vue-Pro 商城模块:从商品管理到交易引擎,50 张表撑起一整套电商系统
java·大数据·vue.js·产品经理·ai编程
码智社5 小时前
AES加密原理详解及Java实现加解密实战
java·开发语言
AI云海5 小时前
python 列表、元组、集合和字典
开发语言·python
萧瑟余晖6 小时前
JDK 26 新特性详解
java·开发语言
马优晨7 小时前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
人邮异步社区8 小时前
怎么把C语言学到精通?
c语言·开发语言
心平气和量大福大9 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
ttwuai9 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
维天说9 小时前
CLI-Switch 2026年3月版历史设计:Hook、TTY 隔离与 JSON 状态
java·服务器·json