IO流-打印流
简介
为
打印而生的IO流
打印流的继承体系
优点
- 高效
- 方便
- 打印的是啥就是啥,不会瞎转(不会把97转成a)
PrintStream
try(
PrintStream ps = new PrintStream("test7.txt", "UTF-8");
){
ps.println(97); // 打印流的优点就是原原本本的打印,不需要转换 这个97不会转换为a
ps.println("Hello, world!");
// write应该是继承了FileOutputStream的方法
ps.write("Hello, world!".getBytes());
}catch (Exception e){
e.printStackTrace();
}
PrintWriter
- PrintWriter 是继承 Writer接口的
- 效果同PrintStream 一致,专用于打印字符的
try(
PrintWriter pw = new PrintWriter("test8.txt", "UTF-8");
){
pw.println(97); // 打印流的优点就是原原本本的打印,不需要转换 这个97不会转换为a
pw.println("Hello, world!");
// write应该是继承了FileOutputStream的方法
pw.write("Hello, world!");
}catch (Exception e){
e.printStackTrace();
}
打印流的应用:输出语句的重定向
其实sout使用的就是系统默认的打印流
System.out.println("老骥伏枥");
System.out.println("志在千里");
try (
PrintStream ps = new PrintStream("test10.txt");
) {
System.setOut(ps);
System.out.println("烈士暮年");
System.out.println("壮心不已");
} catch (Exception e) {
e.printStackTrace();
}
原文地址:https://blog.csdn.net/qq_40603125/article/details/137824739
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!