IO流 p10 打印流

打印 上一主题 下一主题

主题 953|帖子 953|积分 2859

打印流

PrintStream 和 PrintWriter

  1. import java.io.IOException;
  2. import java.io.PrintStream;
  3. /**
  4. * @author: 86199
  5. * @date: 2023/5/7 21:17
  6. * @description: 演示字节打印流/输出流 PrintStream
  7. */
  8. public class PrintStream_ {
  9.     public static void main(String[] args) throws IOException {
  10.         //System.out 在 Java 中也是一个 final 对象引用,
  11.         // 但它的初始化是在 Java 虚拟机启动时完成的,被初始化为一个指向标准输出流的对象。
  12.         //指向的地址不能修改,这个指向的对象本身可以被修改
  13.         PrintStream out = System.out;
  14.         //在默认情况下,PrintStream 输出数据的位置是 标准输出 即显示器
  15.         out.print("Hello World!");
  16.         //因为print()的底层本身就是write(),所以我们可以直接调用write()进行打印/输出
  17.         /* 源码
  18.         public void print(String s) {
  19.             if (s == null) {
  20.                 s = "null";
  21.             }
  22.             write(s);
  23.           }
  24.         */
  25.         out.write("Hello World!".getBytes());
  26.         out.close();
  27.         //我们可以修改打印流输出的位置/设备
  28.         System.setOut(new PrintStream("e:\\f1.txt"));
  29.         System.out.println("Hello World!");//会输出到文件中
  30.         /*
  31.         public static void setOut(PrintStream out) {
  32.             checkIO();
  33.             setOut0(out);//native方法,修改了out
  34.         }
  35.         */
  36.     }
  37. }
复制代码
  1. import java.io.BufferedWriter;
  2. import java.io.FileWriter;
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. /**
  6. * @author: 86199
  7. * @date: 2023/5/7 21:51
  8. * @description: 演示 PrintWriter 使用方式
  9. */
  10. public class PrintWriter_ {
  11.     public static void main(String[] args) throws IOException {
  12. //        PrintWriter printWriter = new PrintWriter(System.out);
  13.         PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
  14.         printWriter.print("三国演义 very good!");
  15.         //不关闭流数据就不会输出
  16.         printWriter.close();
  17.     }
  18. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

尚未崩坏

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表