DataInputStream与DataOutputStream类都是流的装饰者类(java中流的设计采用了装饰者模式),它是用来装饰其它基本的输入流的,比如FileInputStream、ByteArrayInputStream等。首先理解DataInputStream。
DataInputStream类,java的注释是“它允许应用程序以与机器无关方式从底层输入流中读取基本的java数据类型”。也就是说,通过DataInputStream类可以从被装饰的输入流类(FileInputStream、ByteArrayInputStream)中读取java基本数据类型。DataInputStream中的read、readByte、readDouble、readInt等方法比较简单,容易理解。重点理解readUTF方法,源码如下:
//将utf编码的输入流中字节转换为字符串,要想看懂这个方法的代码,需要了解utf-8编码//原理,如果不想深入理解,只要知道这个方法就是将输入流的字节数组按照utf-8编码方//式转换成字符串
public final static String readUTF(DataInput in) throws IOException {
int utflen = in.readUnsignedShort();
byte[] bytearr = null;
char[] chararr = null;
if (in instanceof DataInputStream) {
DataInputStream dis = (DataInputStream)in;
if (dis.bytearr.length < utflen){
dis.bytearr = new byte[utflen*2];
dis.chararr = new char[utflen*2];
}
chararr = dis.chararr;
bytearr = dis.bytearr;
} else {
bytearr = new byte[utflen];
chararr = new char[utflen];
}
int c, char2, char3;
int count = 0;
int chararr_count=0;
in.readFully(bytearr, 0, utflen);
while (count < utflen) {
c = (int) bytearr[count] & 0xff;
if (c > 127) break;
count++;
chararr[chararr_count++]=(char)c;
}
while (count < utflen) {
c = (int) bytearr[count] & 0xff;
switch (c >> 4) {
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
/* 0xxxxxxx*/
count++;
chararr[chararr_count++]=(char)c;
break;
case 12: case 13:
/* 110x xxxx 10xx xxxx*/
count += 2;
if (count > utflen)
throw new UTFDataFormatException(
"malformed input: partial character at end");
char2 = (int) bytearr[count-1];
if ((char2 & 0xC0) != 0x80)
throw new UTFDataFormatException(
"malformed input around byte " + count);
chararr[chararr_count++]=(char)(((c & 0x1F) << 6) |
(char2 & 0x3F));//
break;
case 14:
/* 1110 xxxx 10xx xxxx 10xx xxxx */
count += 3;
if (count > utflen)
throw new UTFDataFormatException(
"malformed input: partial character at end");
char2 = (int) bytearr[count-2];
char3 = (int) bytearr[count-1];
if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
throw new UTFDataFormatException(
"malformed input around byte " + (count-1));
chararr[chararr_count++]=(char)(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
default:
/* 10xx xxxx, 1111 xxxx */
throw new UTFDataFormatException(
"malformed input around byte " + count);
}
}
// The number of chars produced may be less than utflen
return new String(chararr, 0, chararr_count);
}
DataOutputStream是应用程序将java基本类型数据写入到输出流中。例如将java基本类型写入到文件、字节数组等容器中。DataOutputStream继承FilterOutputStream,是装饰者类,用来装饰基本的输出流类,如FileOutputStream、ByteArrayInputStream。