大可制作:QQ群:31564239(asp|jsp|php|mysql)

Java Gossip: PrintWriter

之前曾经介绍过 PrintStream, 它可以将Java的基本数据类型等数据,直接转换为系统默认编码下对应的字节,再输出至OutputStream中,而这边要介绍的 PrintWriter其功能上与PrintStream类似,除了接受OutputStream之外,它还可以接受Writer对象作为输出的对象,当 您原先是使用Writer对象在作处理 ,而现在想要套用println()之类的方法时,使用PrintWriter会是比较方便的作法。

下面这个程序显示了PrintStream与PrintWriter两个对象在处理相同输出目的时的作法,程序将会在荧幕上显示 "简体中文" 四个字节:

  • StreamWriterDemo.java
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简体中文编码的显示。