首页 >> 知识 >> DataInputStream.readUTF返回返回EOFException

DataInputStream.readUTF返回返回EOFException

DataInputStream.readUTF能读取的数据不是一般的数据,实际使用的也不多,一般会配合DataOutStream.writeUTF配合使用,一般的字符串不要使用readUTF读取,否则就会报EOFException的异常,至于为什么会出现这个问题,看下DataInputStream.readUTF以及DataOutStream.writeUTF的源码来解释下:

    public final static String readUTF(DataInput in) throws IOException {         int utflen = in.readUnsignedShort();   //读取字符串长度,所以readUTF能读取的字符串前面有两个字节是真正要读取的字符串的长度         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);

 

    static int writeUTF(String str, DataOutput out) throws IOException {         int strlen = str.length();         int utflen = 0;         int c, count = 0;

        byte[] bytearr = null;         if (out instanceof DataOutputStream) {             DataOutputStream dos = (DataOutputStream)out;             if(dos.bytearr == null || (dos.bytearr.length < (utflen+2)))                 dos.bytearr = new byte[(utflen*2) + 2];             bytearr = dos.bytearr;         } else {             bytearr = new byte[utflen+2];         }

     out.write(bytearr, 0, utflen+2);   //实际写入数据时会在前两个字节写入字符串长度

 

网站地图