Java IO PrintStream,PrintWrite

PrintStream

首先我们常用的静态方法System.out.print()就是一个典型的PrintStream ,请看如下代码证明

import java.io.*;
public class Main {
    public static void main(String[] args) throws IOException ,ClassNotFoundException{
//        得到printStream
        PrintStream out = System.out;
//        打印字符串到默认区域(默认是屏幕)
        out.print("Good Morning");
//        关闭
        out.close();

    }
}

通过查看out.print的源码可以知道底层实际上还是write

还有我们的out.println()的底层实现还有write,只是多个一个换行 。

设置PrintStream打印的位置

通常情况下,我们PrintStream的默认打印位置是屏幕,我们也可以设置PrintStream打印的位置设置为文件。

通过方法 System.setOut()设置打印位置

如下代码实现打印字符到文件

import java.io.*;
public class Main {
    public static void main(String[] args) throws IOException ,ClassNotFoundException{
//        得到printStream
        PrintStream out = System.out;
//        这里设置了打印位置为a.txt文件
        System.setOut(new PrintStream("a.txt"));

//        打印字符串
        System.out.println("good morning");
//        关闭
        out.close();

    }
}

成功的将字符串打印到了a.txt中

 PrintWrite

PrintWrite可以说是printStream的一个封装吧

如下例子使用PrintWrite输出到屏幕

import com.mysql.cj.result.Field;

import java.io.*;
public class Main {
    public static void main(String[] args) throws IOException ,ClassNotFoundException{
//        设置printWriter默认的输出位置是system.out 也就是默认输出位置,屏幕
        PrintWriter printWriter = new PrintWriter(System.out);
//        输出字符串
        printWriter.println("good pancil");
//        一定要记得关闭,这样才会有效果,具体原因可以自己debug追源码
        printWriter.close();
    }
}

效果如下

 

如下例子输出到a.txt文件中

import com.mysql.cj.result.Field;

import java.io.*;
public class Main {
    public static void main(String[] args) throws IOException ,ClassNotFoundException{
//        设置printWriter默认的输出位置是文件
        PrintWriter printWriter = new PrintWriter(new FileWriter("a.txt"));
//        输出字符串
        printWriter.println("good pancil");
//        一定要记得关闭,这样才会有效果,具体原因可以自己debug追源码
        printWriter.close();
    }
}

效果如下

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值