前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >打印流

打印流

作者头像
shimeath
发布2020-07-30 17:08:33
5280
发布2020-07-30 17:08:33
举报

通过使用PrintStream实例输出到文件

原有System.out.println 现改为PrintStream类型的实例.println以完成输出到文件

完整代码

代码语言:javascript
复制
package cn.hxh.io.other;

import java.io.*;

public class PrintStreamDemo01 {

	public static void main(String[] args) throws IOException {
		System.out.println("test");
		PrintStream ps = System.out;
		ps.println("111");
		
		File src = new File("D:/aa/a.txt");
		ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(src)), true);
		ps.println("test1");
	}
}

使用System的setOut方法重定向

通过向setOut方法PrintStream实例进行重新定向到文件 重新定向到控制台:FileDescriptor.out(将原来的file对象替换为这个)

完整代码

代码语言:javascript
复制
package cn.hxh.io.other;

import java.io.*;
import java.util.*;

public class SystemDemo01 {	

	public static void main(String[] args) throws IOException {
//		Scanner in = new Scanner(new BufferedInputStream(new FileInputStream(new File("D:/aa/a.txt"))));
		System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("d:/aa/a.txt"))), true));
		System.out.println();
		System.out.println("test");
		System.out.println("err");
		System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)), true));
		System.out.println("err");
	}
	public static void test1() throws IOException {
		Scanner in = new Scanner(new BufferedInputStream(new FileInputStream(new File("D:/aa/a.txt"))));
		System.out.println(in.nextLine());
		System.out.println("test");
		System.err.println("err");
	}
}

将字节流输入转为字符流,运用字符流方法进行操作

完整代码

代码语言:javascript
复制
package cn.hxh.io.other;

import java.io.*;

public class bufferedIn {

	public static void main(String[] args) throws IOException {
		InputStream is = System.in;
		BufferedReader bis = new BufferedReader(new InputStreamReader(is));
		System.out.println(bis.readLine());

	}

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-01-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 通过使用PrintStream实例输出到文件
    • 完整代码
    • 使用System的setOut方法重定向
      • 完整代码
      • 将字节流输入转为字符流,运用字符流方法进行操作
        • 完整代码
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档