打印流PrintStream---装饰设计

    PrintStream 为其他输出流添加了功能,使它们能够方便地打印各种数据值表示形式。它还提供其他两项功能。与其他输出流不同, PrintStream 永远不会抛出 IOException;而是,异常情况仅设置可通过 checkError 方法测试的内部标志。另外,为了自动刷新,可以创建一个 PrintStream;这意味着可在写入 byte 数组之后自动调用 flush 方法,可调用其中一个 println 方法,或写入一个换行符或字节 ( '\n')。
    PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。

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"))) ;
//以下代码实际上是将FileOutputStream类的功能包装类一下,这样的设计在Java中我们称之为装饰设计

    ps.print("hello ") ;
    ps.println("world!!!") ;
    ps.print("1 + 1 = " + 2) ;
    ps.close() ;
  }
};

 

格式化输出

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() ;
  }
};
如果觉得以上代码中%不好记可以将其全部写成%s.看代码
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() ;
  }
};
分享至
一键收藏,随时查看,分享好友!
0人
了这篇文章
类别: Java┆阅读( 0)┆评论( 0) ┆ 返回博主首页┆ 返回博客首页
上一篇 管道流 下一篇 回文数

你可能感兴趣的:(打印流PrintStream---装饰设计)