打印流

打印流

在整个 IO 包中,打印流是输出信息最方便的类,主要包含字节打印流(PrintStream) 和字符打印流(PrintWriter) . 打印流提供了非常方便的打印功能,可以打印任何的数据类型,例如: 小数、整数、字符串等等。

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


在这个类中定义了很多print() 或println() 方法。System.out.println(), 此方法可以打印任何数据类型。

构造方法:

public PrintStream(OutputStream out) -->指定输出位置。

此构造方法接收OutputStream 的子类。

使用 PrintStream 输出信息

[java]  view plain  copy
  1. import java.io.* ;  
  2. public class PrintDemo01{  
  3.     public static void main(String arg[]) throws Exception{  
  4.         PrintStream ps = null ;     // 声明打印流对象  
  5.         // 如果现在是使用FileOuputStream实例化,意味着所有的输出是向文件之中  
  6.         ps = new PrintStream(new FileOutputStream(new File("d:" + File.separator + "test.txt"))) ;  
  7.         ps.print("hello ") ;  
  8.         ps.println("world!!!") ;  
  9.         ps.print("1 + 1 = " + 2) ;  
  10.         ps.close() ;  
  11.     }  
  12. };  

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

2、格式化输出

如果学习过其他语言,比较代表性的就是C语言。

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

如果,觉得以上的要写很多%s、%d 无法记住的话呢,实际上也可以简单操作,全部使用%s表示。


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

1、PrintStream 可以方便的完成输出的功能。

2、在以后的输出中基本上都使用PrintStream 完成,因为比较方便一些。

3、PrintStream 属于装饰设计模式。





转载于:https://www.cnblogs.com/Jxiaobai/p/6622201.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值