Java IO--打印流PrintStream
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() ;
}
};
最後更新:2017-04-03 14:54:00