Java中io流的学习(八)PrintStream和PrintWriter

PrintStream(可以将字节流封装成打印流)继承于FilterOutputStream,FilterOutputStream是继承于OutputStream的;PrintWriter(可以将字节流、字符流封装成打印流)继承于Writer的。

其中可以使用PrintStream进行重定向的操作:

系统标准输入流的方向:控制台 -> 程序,重新定义系统标准输入流使用的方向System.setIn(),重新定义后的方向为:文件->程序

系统的标准输出流的方向:程序->控制台,重定向系统标准输出流使用的方法System.setOut(),重新定义后的方向为:程序->文件

关于其的一些常用方法,这里不做多的介绍,API中已经很完善了,需要用的时候参照API即可。

下面通过实例代码来对其进行学习:

①使用PrintStream进行打印到文件的操作

	@Test
	public void t1() throws Exception{
		PrintStream ps = new PrintStream(new FileOutputStream("H:\\javaio\\testofprint.txt"));
		ps.print("我是打印流测试(PrintStream)");
		ps.close();
	}

②使用PrintWriter进行打印到文件的操作

	@Test
	public void t2() throws Exception{
		PrintWriter pw = new PrintWriter(new FileWriter("H:\\javaio\\testofprint.txt"));
		pw.write("我是打印流测试(PrintWriter)");
		pw.close();
	}

③使用打印流进行重定向的操作,从文件读取内容到程序

	@Test
	public void t3() throws Exception{

		System.setIn(new FileInputStream("H:\\javaio\\testofprint.txt"));
		
		Scanner input = new Scanner(System.in);
		String next = input.next();
		System.out.println(next);
		input.close();
	}

④使用打印流进行重定向的操作,从程序到文件

	//使用打印流进行重定向操作,从程序将内容打印到文件
	@Test
	public void t4() throws Exception{
		System.setOut(new PrintStream("H:\\javaio\\testofprint.txt"));
		System.out.println("我是打印流重定向操作");
	}
扫描二维码关注公众号,回复: 2826060 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_41061437/article/details/81782770