前面曾介紹過PrintStream,它可以將Java的基礎資料型別 (Elementary Data Type)等資料,直接轉換為系統預設編碼下對應的字元,再輸出至OutputStream中。而這裡要介紹的 java.io.PrintWriter在功能上與PrintStream類似,除了接受OutputStream執行個體作為變數之外,PrintWriter還可以接受Writer對象作為輸出的對象。當原先是使用Writer對象在作字元處理,而現在想要套用println()之類的方法時,使用PrintWriter會是比較方便的作法。
下面的例子顯示了PrintStream與PrintWriter兩個對象在處理相同輸出目的時的作法,程式會輸出簡體中文GB2312編碼的文字至指定的檔案中。
import java.io.*;import java.util.*;public class StreamWriterDemo{public static void main(String[] args) {try{ // 「簡體中文」四個字的 GB2312 編碼 byte[] sim = {(byte)0xbc, (byte)0xf2, (byte)0xcc, (byte)0xe5, (byte)0xd6, (byte)0xd0, (byte)0xce, (byte)0xc4};//數組作為流來源ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(sim);InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream,"GB2312");//PrintWriter可以接受Writer執行個體作為變數 PrintWriter printWriter = new PrintWriter( new OutputStreamWriter( new FileOutputStream(args[0]),"GB2312"));int in = 0;printWriter.print("PrintWriter: ");//寫入數組內容while((in = inputStreamReader.read())!=-1){printWriter.print((char)in);}printWriter.println();printWriter.close();byteArrayInputStream.reset(); //PrintStream接受OutputStream執行個體作為變數PrintStream printStream = new PrintStream(new FileOutputStream(args[0],true),true,"GB2312");printStream.print("PrintStream: ");//寫入數組內容while((in = inputStreamReader.read()) != -1){printStream.print((char)in);System.out.println(Integer.toHexString(in));} printStream.println();inputStreamReader.close();printStream.close(); }catch(ArrayIndexOutOfBoundsException e){System.out.println("沒有指定檔案");}catch(IOException e){e.printStackTrace();}}} 運行如下命令 java StreamWriterDemo Output.txt 螢幕上會輸出:
7b80
4f53
4e2d
6587
"簡體中文" 對應的Unicode 編碼值。