java标准IO

java的标准IO指的是System.in,System.out,System.err,在默认的情况下in代表键盘和out代表显示器,当程序通过System.in来获得输入时,实际上是通过键盘获得输入,当程序通过System.out执行输出时,程序总是输出到屏幕,其中in是基本IO类型InputStream,而out和err是javaIO的一种装饰器PrintStream,那么什么是PrintStream.

PrintStream

PrintStream是打印输出流,继承自FilterOutputStream是java io API装饰模式的一种实现。设计此类的目的是能够方便的打印种类繁多的数据类型.PrintStream永远不会抛出IOException,它产生的IOException会被自身的函数捕获并设置错误标记,用户可以通过checkError()查看错误标记了解PrintStream是否发生了IOException

PrintStream的初始化

与其它的FilterOutputStream装饰器一样,在初始化的时候需要传入一个输出流out作为参数,或者传入一个文件名,PrintStream会利用文件名构造一个输出流
我们也可以根据实际需要设定该PrintStream是否自动刷新以及字符集.如果我们在构造PrintStream时候没有设定自动刷新属性那么每次执行print打印操作时需要手动调用flush

下面是几个常用的构造方法

// 将“输出流out”作为PrintStream的输出流,不会自动flush,并且采用默认字符集
PrintStream(OutputStream out)
// 将“输出流out”作为PrintStream的输出流,自动flush,并且采用默认字符集。
PrintStream(OutputStream out, boolean autoFlush)
// 将“输出流out”作为PrintStream的输出流,自动flush,采用charsetName字符集。
PrintStream(OutputStream out, boolean autoFlush, String charsetName)
// 创建fileName对应的FileOutputStream,然后将该FileOutputStream作为PrintStream的输出流,不自动flush,采用charsetName字符集。
PrintStream(String fileName, String charsetName)

与DataoutputStream异同

看到PrintStream我们可能会想到DataOutputStream,PrintStream与DataOutputStream不同点在于
1. PrintStream可以指定数据编码,如果没有指定会采用系统默认的字符编码而DataOutputstream采用UTF-8编码
2. DataOutputStream会抛出IOException而PrintStream会隐藏打印数据时候的错误
3. PrintStream与DataOutputStream的设计目的也不一样,DataOutputstream的目的是允许程序以与机器无关的方式从底层读写java数据类型,而PrintStream的目的是为其它输出流提供打印各种数据值的表示形式

System.in

讲完了PrintStream,我们再来看看System.in,因为in是基本的IO类型InputStream,这意味着我们在使用System.in的时候,我们要对其进行包装,否则我们读到的数据都是字节类型.

从控制台读取字符串

这个场景我们经常遇到,因为我们要的是字符型数据,所以我们要讲InputStream转化为Reader型,使用BufferedReader缓存数据

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String command = br.readLine();

重定向标准IO

有时候我们需要将控制台的数据打印到文件,那么这个时候我们就需要重定向标准IO
重定向标准IO的三个函数分别是
System.setIn
System.setOut
System.setOut

//保存原始System.out,in的引用
PrintStream console = System.out;
InputStream keyboard = System.in;
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream("filepath1");
     PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream("filepath2"))))
    System.setIn(in);
    System.setOut(out);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String str;
    while ((str = br.readLine()) != null) {
        System.out.println(str);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    //重新设置原始引用
    System.setOut(console);
    System.setIn(keyboard);
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值