Java IO--打印流PrintStream

1、打印流:


之前在打印信息的时候需要使用OutputStream,但是这样一来,所有的数据输出的时候会非常的麻烦,String->byte[], 打印流中可以方便的进行输出。
Java IO--打印流PrintStream_第1张图片
Java IO--打印流PrintStream_第2张图片

2、打印流的好处

Java IO--打印流PrintStream_第3张图片
使用PrintStream输出信息:
import java.io.* ;
public class PrintDemo01{
	public static void main(String arg[]) throws Exception{
		PrintStream ps = null ;		// 声明打印流对象
		// 如果现在是使用FileOuputStream实例化,意味着所有的输出是向文件之中
		ps = new PrintStream(new FileOutputStream(new File("d:" + File.separator + "test.txt"))) ;
		ps.print("hello ") ;
		ps.println("world!!!") ;
		ps.print("1 + 1 = " + 2) ;
		ps.close() ;
	}
};

此时实际上是将FileOutputStream类的功能包装了一下,这样的设计在java中称为装饰设计。

3、格式化输出:

Java IO--打印流PrintStream_第4张图片
import java.io.* ;
public class PrintDemo02{
	public static void main(String arg[]) throws Exception{
		PrintStream ps = null ;		// 声明打印流对象
		// 如果现在是使用FileOuputStream实例化,意味着所有的输出是向文件之中
		ps = new PrintStream(new FileOutputStream(new File("d:" + File.separator + "test.txt"))) ;
		String name = "李兴华" ;	// 定义字符串
		int age = 30 ;				// 定义整数
		float score = 990.356f ;	// 定义小数
		char sex = 'M' ;			// 定义字符
		ps.printf("姓名:%s;年龄:%d;成绩:%f;性别:%c",name,age,score,sex) ;
		ps.close() ;
	}
};


import java.io.* ;
public class PrintDemo03{
	public static void main(String arg[]) throws Exception{
		PrintStream ps = null ;		// 声明打印流对象
		// 如果现在是使用FileOuputStream实例化,意味着所有的输出是向文件之中
		ps = new PrintStream(new FileOutputStream(new File("d:" + File.separator + "test.txt"))) ;
		String name = "李兴华" ;	// 定义字符串
		int age = 30 ;				// 定义整数
		float score = 990.356f ;	// 定义小数
		char sex = 'M' ;			// 定义字符
		ps.printf("姓名:%s;年龄:%s;成绩:%s;性别:%s",name,age,score,sex) ;
		ps.close() ;
	}
};


你可能感兴趣的:(Java IO--打印流PrintStream)