打印流

PrintStream 和 PrintWriter

import java.io.IOException;
import java.io.PrintStream;

/**
 * @author: 86199
 * @date: 2023/5/7 21:17
 * @description: 演示字节打印流/输出流 PrintStream
 */
public class PrintStream_ {
    public static void main(String[] args) throws IOException {
        //System.out 在 Java 中也是一个 final 对象引用,
        // 但它的初始化是在 Java 虚拟机启动时完成的,被初始化为一个指向标准输出流的对象。
        //指向的地址不能修改,这个指向的对象本身可以被修改
        PrintStream out = System.out;
        //在默认情况下,PrintStream 输出数据的位置是 标准输出 即显示器
        out.print("Hello World!");
        //因为print()的底层本身就是write(),所以我们可以直接调用write()进行打印/输出
        /* 源码
        public void print(String s) {
            if (s == null) {
                s = "null";
            }
            write(s);
          }
        */
        out.write("Hello World!".getBytes());
        out.close();

        //我们可以修改打印流输出的位置/设备
        System.setOut(new PrintStream("e:\f1.txt"));
        System.out.println("Hello World!");//会输出到文件中
        /*
        public static void setOut(PrintStream out) {
            checkIO();
            setOut0(out);//native方法,修改了out
        }
        */
    }
}

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: 86199
 * @date: 2023/5/7 21:51
 * @description: 演示 PrintWriter 使用方式
 */
public class PrintWriter_ {
    public static void main(String[] args) throws IOException {
//        PrintWriter printWriter = new PrintWriter(System.out);
        PrintWriter printWriter = new PrintWriter(new FileWriter("e:\f2.txt"));
        printWriter.print("三国演义 very good!");
        //不关闭流数据就不会输出
        printWriter.close();
    }
}

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/zh-Note/p/17455321.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!