Java IO--打印流PrintStream

来源:互联网 发布:寒冷队长 知乎 编辑:程序博客网 时间:2024/06/10 07:31

1、打印流:


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


2、打印流的好处


使用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、格式化输出:


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() ;}};


原创粉丝点击