Reader、Writer支持Unicode标准字节集(Character set)(位元组串流则只支持ISO-Latin-1 8-bit),在处理串流时,会根据系统默认的字节编码来进行字节转换,它们是抽象类,真正您会使用其子类,子类通常会覆盖相关的方法。
在 PushbackInputStream
中,您读入一个含BIG5中文字及ASCII字节的文字文件,这边改写一下这个例子,使用Reader的子类
InputStreamReader来转换读入的两个位元组为中文字节,并显示在荧幕上:
package onlyfun.caterpillar; import java.io.*; public class ReaderDemo { public static void main(String[] args) { try { PushbackInputStream pushbackInputStream = new PushbackInputStream( new FileInputStream(args[0])); byte[] array = new byte[2];
ByteArrayInputStream byteArrayStream = new ByteArrayInputStream(array);
// reader会从已读的位元数组中取出数据 InputStreamReader reader = new InputStreamReader(byteArrayStream);
int tmp = 0; int count = 0;
while((count = pushbackInputStream.read(array)) != -1) { // 两个位元组转换为整数 tmp = (short)((array[0] << 8) | (array[1] & 0xff)); tmp = tmp & 0xFFFF; // 判断是否为BIG5,如果是则显示BIG5中文字 if(tmp >= 0xA440 && tmp < 0xFFFF) { System.out.println("BIG5: " + (char)reader.read()); // 重置ArrayInputStream的读取游标 // 下次reader才会再重头读取数据 byteArrayStream.reset(); } else { // 将第二个位元组推回串流 pushbackInputStream.unread(array, 1, 1); // 显示ASCII范围的字节 System.out.println("ASCII: " + (char)array[0]); } } pushbackInputStream.close(); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("请指定文件名称"); } catch(IOException e) { e.printStackTrace(); } } }
假设的文字文件中有以下的文字:"这T是e一s个t测试" ,执行结果会是:
BIG5: 这
ASCII: T
BIG5: 是
ASCII: e
BIG5: 一
ASCII: s
BIG5: 个
ASCII: t
BIG5: 测
BIG5: 试
ASCII: !
EOF
|
InputStreamReader可以用位元组串流中取出位元组数据,并进行字节处理动作,关于Reader、Writer相关子类,之后会于各相关主题进行介绍。 |