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 + 关闭流
    }
}
相关推荐
码云骑士1 天前
【2.Java基础】Java常量与变量-从基本类型到类型转换全面掌握
java·开发语言
AI玫瑰助手1 天前
Python函数:匿名函数lambda的定义与使用场景
android·java·python
爱和冰阔落1 天前
Ollama 本地大模型部署实战:从安装到 RAG 知识库完整指南
开发语言·大模型·php·ollama
泡^泡1 天前
Python数据类型与运算符
开发语言·windows·python
刃神太酷啦1 天前
MySQL 库表操作 +数据类型+ 基础概念全梳理----《Hello MySQL!》(2)
java·c语言·数据库·c++·vscode·mysql·adb
不爱编程的小陈1 天前
Go语言GMP调度模型深度解析:高并发背后的精妙设计
开发语言·后端·golang
李子琪。1 天前
谷歌“三剑客”与云计算基石:GFS、MapReduce、Bigtable 全栈解析及私有云落地实践
开发语言·编辑器·perl
YDS8291 天前
DeepSeek RAG&MCP + Agent智能体项目 —— 集成ELK日志管理系统和Prometheus监控系统
java·elk·ai·springboot·agent·prometheus·deepseek
xufengzhu1 天前
Python库PyMySQL的使用指南
开发语言·python·pip
骄马之死1 天前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端