之前曾經介紹過 PrintStream,
它可以將Java的基本資料型態等資料,直接轉換為系統預設編碼下對應的字元,再輸出至OutputStream中,而這邊要介紹的
PrintWriter其功能上與PrintStream類似,除了接受OutputStream之外,它還可以接受Writer物件作為輸出的對象,當
您原先是使用Writer物件在作處理 ,而現在想要套用println()之類的方法時,使用PrintWriter會是比較方便的作法。
下面這個程式顯示了PrintStream與PrintWriter兩個物件在處理相同輸出目的時的作法,程式將會在螢幕上顯示 "简体中文"
四個字元:
package onlyfun.caterpillar; import java.io.*; public class StreamWriterDemo { public static void main(String[] args) { try { byte[] sim = {(byte)0xbc, (byte)0xf2, // 简 (byte)0xcc, (byte)0xe5, // 体 (byte)0xd6, (byte)0xd0, // 中 (byte)0xce, (byte)0xc4}; // 文 InputStreamReader inputStreamReader = new InputStreamReader( new ByteArrayInputStream(sim), "GB2312"); PrintWriter printWriter = new PrintWriter( new OutputStreamWriter(System.out, "GB2312")); PrintStream printStream = new PrintStream(System.out, true, "GB2312"); int in; while((in = inputStreamReader.read()) != -1) { printWriter.println((char)in); printStream.println((char)in); } inputStreamReader.close(); printWriter.close(); printStream.close(); } catch(ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } } }
要能正確看到執行的結果,您的終端機程式必須支援GB2312簡體中文編碼的顯示。 |
|