程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java io學習(十三) 數據輸入流的認知、源碼和示例

java io學習(十三) 數據輸入流的認知、源碼和示例

編輯:關於JAVA

DataInputStream(數據輸入流)的認知、源碼和示例

DataInputStream 介紹

DataInputStream 是數據輸入流。它繼承於FilterInputStream。

DataInputStream 是用來裝飾其它輸入流,它“允許應用程序以與機器無關方式從底層輸入流中讀取基本 Java 數據類型”。應用程序可以使用DataOutputStream(數據輸出流)寫入由DataInputStream(數據輸入流)讀取的數據。

DataInputStream 函數列表

DataInputStream(InputStream in)
final int     read(byte[] buffer, int offset, int length)
final int     read(byte[] buffer)
final boolean     readBoolean()
final byte     readByte()
final char     readChar()
final double     readDouble()
final float     readFloat()
final void     readFully(byte[] dst)
final void     readFully(byte[] dst, int offset, int byteCount)
final int     readInt()
final String     readLine()
final long     readLong()
final short     readShort()
final static String     readUTF(DataInput in)
final String     readUTF()
final int     readUnsignedByte()
final int     readUnsignedShort()
final int     skipBytes(int count)

DataInputStream.java源碼分析(基於jdk1.7.40)

package java.io;
     
public class DataInputStream extends FilterInputStream implements DataInput {
     
    // 構造函數。
    public DataInputStream(InputStream in) {
        super(in);
    }
     
    private byte bytearr[] = new byte[80];
    private char chararr[] = new char[80];
     
    // 從“數據輸入流”中讀取一個字節
    public final int read(byte b[]) throws IOException {
        return in.read(b, 0, b.length);
    }
     
    // 從“數據輸入流”中讀取數據並存儲到字節數組b中。
    // off是字節數組b中開始存儲元素的起始位置。
    // len是讀取字節的個數。
    public final int read(byte b[], int off, int len) throws IOException {
        return in.read(b, off, len);
    }
     
    // 從“數據輸入流”中讀取數據並填滿字節數組b中;沒有填滿數組b則一直讀取,直到填滿位置。
    // 從字節數組b的位置0開始存儲,並且讀取的字節個數等於b的長度。
    public final void readFully(byte b[]) throws IOException {
        readFully(b, 0, b.length);
    }
     
    // 從“數據輸入流”中讀取數據並存儲到字節數組b中;若沒讀取len個字節,直到一直讀取直到讀取完len個字節為止。
    public final void readFully(byte b[], int off, int len) throws IOException {
        if (len < 0)
            throw new IndexOutOfBoundsException();
        int n = 0;
        while (n < len) {
            int count = in.read(b, off + n, len - n);
            if (count < 0)
                throw new EOFException();
            n += count;
        }
    }
     
    // 跳過n個字節
    public final int skipBytes(int n) throws IOException {
        int total = 0;
        int cur = 0;
     
        while ((total<n) && ((cur = (int) in.skip(n-total)) > 0)) {
            total += cur;
        }
     
        return total;
    }
     
    // 從“數據輸入流”中讀取boolean類型的值
    public final boolean readBoolean() throws IOException {
        int ch = in.read();
        if (ch < 0)
            throw new EOFException();
        return (ch != 0);
    }
     
    // 從“數據輸入流”中讀取Byte類型的值
    public final byte readByte() throws IOException {
        int ch = in.read();
        if (ch < 0)
            throw new EOFException();
        return (byte)(ch);
    }
     
    // 從“數據輸入流”中讀取“無符號的Byte類型”的值,即讀取值為正數的byte值
    public final int readUnsignedByte() throws IOException {
        int ch = in.read();
        if (ch < 0)
            throw new EOFException();
        return ch;
    }
     
    // 從“數據輸入流”中讀取“short類型”的值
    public final short readShort() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        if ((ch1 | ch2) < 0)
            throw new EOFException();
        return (short)((ch1 << 8) + (ch2 << 0));
    }
     
    // 從“數據輸入流”中讀取“無符號的short類型”的值
    public final int readUnsignedShort() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        if ((ch1 | ch2) < 0)
            throw new EOFException();
        return (ch1 << 8) + (ch2 << 0);
    }
     
    // 從“數據輸入流”中讀取“char類型”的值
    public final char readChar() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        if ((ch1 | ch2) < 0)
            throw new EOFException();
        return (char)((ch1 << 8) + (ch2 << 0));
    }
     
    // 從“數據輸入流”中讀取“int類型”的值
    public final int readInt() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        int ch3 = in.read();
        int ch4 = in.read();
        if ((ch1 | ch2 | ch3 | ch4) < 0)
            throw new EOFException();
        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
    }
     
    private byte readBuffer[] = new byte[8];
     
    // 從“數據輸入流”中讀取“long類型”的值
    public final long readLong() throws IOException {
        readFully(readBuffer, 0, 8);
        return (((long)readBuffer[0] << 56) +
                ((long)(readBuffer[1] & 255) << 48) +
                ((long)(readBuffer[2] & 255) << 40) +
                ((long)(readBuffer[3] & 255) << 32) +
                ((long)(readBuffer[4] & 255) << 24) +
                ((readBuffer[5] & 255) << 16) +
                ((readBuffer[6] & 255) <<  8) +
                ((readBuffer[7] & 255) <<  0));
    }
     
    // 從“數據輸入流”中讀取“float類型”的值
    public final float readFloat() throws IOException {
        return Float.intBitsToFloat(readInt());
    }
     
    // 從“數據輸入流”中讀取“double類型”的值
    public final double readDouble() throws IOException {
        return Double.longBitsToDouble(readLong());
    }
     
    private char lineBuffer[];
     
    @Deprecated
    public final String readLine() throws IOException {
        char buf[] = lineBuffer;
     
        if (buf == null) {
            buf = lineBuffer = new char[128];
        }
     
        int room = buf.length;
        int offset = 0;
        int c;
     
loop:   while (true) {
            switch (c = in.read()) {
              case -1:
              case '\n':
                break loop;
     
              case '\r':
                int c2 = in.read();
                if ((c2 != '\n') && (c2 != -1)) {
                    if (!(in instanceof PushbackInputStream)) {
                        this.in = new PushbackInputStream(in);
                    }
                    ((PushbackInputStream)in).unread(c2);
                }
                break loop;
     
              default:
                if (--room < 0) {
                    buf = new char[offset + 128];
                    room = buf.length - offset - 1;
                    System.arraycopy(lineBuffer, 0, buf, 0, offset);
                    lineBuffer = buf;
                }
                buf[offset++] = (char) c;
                break;
            }
        }
        if ((c == -1) && (offset == 0)) {
            return null;
        }
        return String.copyValueOf(buf, 0, offset);
    }
     
    // 從“數據輸入流”中讀取“UTF類型”的值
    public final String readUTF() throws IOException {
        return readUTF(this);
    }
     
    public final static String readUTF(DataInput in) throws IOException {
        // 從“數據輸入流”中讀取“無符號的short類型”的值:
        // 注意:UTF-8輸入流的前2個字節是數據的長度
        int utflen = in.readUnsignedShort();
        byte[] bytearr = null;
        char[] chararr = null;
     
        // 如果in本身是“數據輸入流”,
        // 則,設置字節數組bytearr = "數據輸入流"的成員bytearr
        //     設置字符數組chararr = "數據輸入流"的成員chararr
        // 否則的話,新建數組bytearr和chararr
        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;
     
        // 從“數據輸入流”中讀取數據並存儲到字節數組bytearr中;從bytearr的位置0開始存儲,存儲長度為utflen。
        // 注意,這裡是存儲到字節數組!而且讀取的是全部的數據。
        in.readFully(bytearr, 0, utflen);
     
        // 將“字節數組bytearr”中的數據 拷貝到 “字符數組chararr”中
        // 注意:這裡相當於“預處理的輸入流中單字節的符號”,因為UTF-8是1-4個字節可變的。
        while (count < utflen) {
            // 將每個字節轉換成int值
            c = (int) bytearr[count] & 0xff;
            // UTF-8的單字節數據的值都不會超過127;所以,超過127,則退出。
            if (c > 127) break;
            count++;
            // 將c保存到“字符數組chararr”中
            chararr[chararr_count++]=(char)c;
        }
     
        // 處理完輸入流中單字節的符號之後,接下來我們繼續處理。
        while (count < utflen) {
            // 下面語句執行了2步操作。
            // (01) 將字節由 “byte類型” 轉換成 “int類型”。
            //      例如, “11001010” 轉換成int之後,是 “00000000 00000000 00000000 11001010”
            // (02) 將 “int類型” 的數據左移4位
            //      例如, “00000000 00000000 00000000 11001010” 左移4位之後,變成 “00000000 00000000 00000000 00001100”
            c = (int) bytearr[count] & 0xff;
            switch (c >> 4) {
                // 若 UTF-8 是單字節,即 bytearr[count] 對應是 “0xxxxxxx” 形式;
                // 則 bytearr[count] 對應的int類型的c的取值范圍是 0-7。
                case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
                    /* 0xxxxxxx*/
                    count++;
                    chararr[chararr_count++]=(char)c;
                    break;
     
                // 若 UTF-8 是雙字節,即 bytearr[count] 對應是 “110xxxxx  10xxxxxx” 形式中的第一個,即“110xxxxx”
                // 則 bytearr[count] 對應的int類型的c的取值范圍是 12-13。
                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;
     
                // 若 UTF-8 是三字節,即 bytearr[count] 對應是 “1110xxxx  10xxxxxx  10xxxxxx” 形式中的第一個,即“1110xxxx”
                // 則 bytearr[count] 對應的int類型的c的取值是14 。
                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;
     
                // 若 UTF-8 是四字節,即 bytearr[count] 對應是 “11110xxx 10xxxxxx  10xxxxxx  10xxxxxx” 形式中的第一個,即“11110xxx”
                // 則 bytearr[count] 對應的int類型的c的取值是15 
                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);
    }
}

說明:

DataInputStream 的作用就是“允許應用程序以與機器無關方式從底層輸入流中讀取基本 Java 數據類型。應用程序可以使用數據輸出流寫入稍後由數據輸入流讀取的數據。”

DataInputStream 中比較難以理解的函數就只有 readUTF(DataInput in);下面,對這個函數進行詳細的介紹,其它的函數請參考源碼中的注釋。

readUTF(DataInput in)源碼如下:

public final static String readUTF(DataInput in) throws IOException {
    // 從“數據輸入流”中讀取“無符號的short類型”的值:
    // 注意:UTF-8輸入流的前2個字節是數據的長度
    int utflen = in.readUnsignedShort();
    byte[] bytearr = null;
    char[] chararr = null;
     
    // 如果in本身是“數據輸入流”,
    // 則,設置字節數組bytearr = "數據輸入流"的成員bytearr
    //     設置字符數組chararr = "數據輸入流"的成員chararr
    // 否則的話,新建數組bytearr和chararr
    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;
     
    // 從“數據輸入流”中讀取數據並存儲到字節數組bytearr中;從bytearr的位置0開始存儲,存儲長度為utflen。
    // 注意,這裡是存儲到字節數組!而且讀取的是全部的數據。
    in.readFully(bytearr, 0, utflen);
     
    // 將“字節數組bytearr”中的數據 拷貝到 “字符數組chararr”中
    // 注意:這裡相當於“預處理的輸入流中單字節的符號”,因為UTF-8是1-4個字節可變的。
    while (count < utflen) {
        // 將每個字節轉換成int值
        c = (int) bytearr[count] & 0xff;
        // UTF-8的每個字節的值都不會超過127;所以,超過127,則退出。
        if (c > 127) break;
        count++;
        // 將c保存到“字符數組chararr”中
        chararr[chararr_count++]=(char)c;
    }
     
    // 處理完輸入流中單字節的符號之後,接下來我們繼續處理。
    while (count < utflen) {
        // 下面語句執行了2步操作。
        // (01) 將字節由 “byte類型” 轉換成 “int類型”。
        //      例如, “11001010” 轉換成int之後,是 “00000000 00000000 00000000 11001010”
        // (02) 將 “int類型” 的數據左移4位
        //      例如, “00000000 00000000 00000000 11001010” 左移4位之後,變成 “00000000 00000000 00000000 00001100”
        c = (int) bytearr[count] & 0xff;
        switch (c >> 4) {
            // 若 UTF-8 是單字節,即 bytearr[count] 對應是 “0xxxxxxx” 形式;
            // 則 bytearr[count] 對應的int類型的c的取值范圍是 0-7。
            case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
                /* 0xxxxxxx*/
                count++;
                chararr[chararr_count++]=(char)c;
                break;
     
            // 若 UTF-8 是雙字節,即 bytearr[count] 對應是 “110xxxxx  10xxxxxx” 形式中的第一個,即“110xxxxx”
            // 則 bytearr[count] 對應的int類型的c的取值范圍是 12-13。
            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;
     
            // 若 UTF-8 是三字節,即 bytearr[count] 對應是 “1110xxxx  10xxxxxx  10xxxxxx” 形式中的第一個,即“1110xxxx”
			// 查看本欄目
			
		
		

說明:

(01) readUTF()的作用,是從輸入流中讀取UTF-8編碼的數據,並以String字符串的形式返回。

(02) 知道了readUTF()的作用之後,下面開始介紹readUTF()的流程:

第1步,讀取出輸入流中的UTF-8數據的長度。代碼如下:

int utflen = in.readUnsignedShort();

UTF-8數據的長度包含在它的前兩個字節當中;我們通過readUnsignedShort()讀取出前兩個字節對應的正整數就是UTF-8數據的長度。

第2步,創建2個數組:字節數組bytearr 和 字符數組chararr。代碼如下:

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];
}

首先,判斷該輸入流本身是不是DataInputStream,即數據輸入流;若是的話,

則,設置字節數組bytearr = "數據輸入流"的成員bytearr

 設置字符數組chararr = "數據輸入流"的成員chararr

否則的話,新建數組bytearr和chararr。

第3步,將UTF-8數據全部讀取到“字節數組bytearr”中。代碼如下:

in.readFully(bytearr, 0, utflen);

注意: 這裡是存儲到字節數組,而不是字符數組!而且讀取的是全部的數據。

第4步,對UTF-8中的單字節數據進行預處理。代碼如下:

while (count < utflen) {
    // 將每個字節轉換成int值
    c = (int) bytearr[count] & 0xff;
    // UTF-8的單字節數據的值都不會超過127;所以,超過127,則退出。
    if (c > 127) break;
    count++;
    // 將c保存到“字符數組chararr”中
    chararr[chararr_count++]=(char)c;
}

UTF-8的數據是變長的,可以是1-4個字節;在readUTF()中,我們最終是將全部的UTF-8數據保存到“字符數組(而不是字節數組)”中,再將其轉換為String字符串。

由於UTF-8的單字節和ASCII相同,所以這裡就將它們進行預處理,直接保存到“字符數組chararr”中。對於其它的UTF-8數據,則在後面進行處理。

第5步,對“第4步 預處理”之後的數據,接著進行處理。代碼如下:

// 處理完輸入流中單字節的符號之後,接下來我們繼續處理。
while (count < utflen) {
    // 下面語句執行了2步操作。
    // (01) 將字節由 “byte類型” 轉換成 “int類型”。
    //      例如, “11001010” 轉換成int之後,是 “00000000 00000000 00000000 11001010”
    // (02) 將 “int類型” 的數據左移4位
    //      例如, “00000000 00000000 00000000 11001010” 左移4位之後,變成 “00000000 00000000 00000000 00001100”
    c = (int) bytearr[count] & 0xff;
    switch (c >> 4) {
        // 若 UTF-8 是單字節,即 bytearr[count] 對應是 “0xxxxxxx” 形式;
        // 則 bytearr[count] 對應的int類型的c的取值范圍是 0-7。
        case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
            /* 0xxxxxxx*/
            count++;
            chararr[chararr_count++]=(char)c;
            break;
     

        // 若 UTF-8 是雙字節,即 bytearr[count] 對應是 “110xxxxx  10xxxxxx” 形式中的第一個,即“110xxxxx”
        // 則 bytearr[count] 對應的int類型的c的取值范圍是 12-13。
        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;
     
        // 若 UTF-8 是三字節,即 bytearr[count] 對應是 “1110xxxx  10xxxxxx  10xxxxxx” 形式中的第一個,即“1110xxxx”
        // 則 bytearr[count] 對應的int類型的c的取值是14 。
        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;
     
        // 若 UTF-8 是四字節,即 bytearr[count] 對應是 “11110xxx 10xxxxxx  10xxxxxx  10xxxxxx” 形式中的第一個,即“11110xxx”
        // 則 bytearr[count] 對應的int類型的c的取值是15 
        default:
            /* 10xx xxxx,  1111 xxxx */
            throw new UTFDataFormatException(
                "malformed input around byte " + count);
    }
}

(a) 我們將下面的兩條語句一起進行說明

c = (int) bytearr[count] & 0xff;

switch (c >> 4) { ... }

首先,我們必須要理解 為什麼要這麼做(執行上面2條語句)呢?

原因很簡單,這麼做的目的就是為了區分UTF-8數據是幾位的;因為UTF-8的數據是1~4字節不等。

我們先看看UTF-8在1~4位情況下的格式。

--------------------+---------------------------------------------

1字節 UTF-8的通用格式  | 0xxxxxxx

2字節 UTF-8的通用格式  | 110xxxxx 10xxxxxx

3字節 UTF-8的通用格式  | 1110xxxx 10xxxxxx 10xxxxxx

4字節 UTF-8的通用格式  | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

執行 c = (int) bytearr[count] & 0xff; 和 c>>4 這2項操作之後,上面的數據變成

--------------------+---------------------------------------------

1字節 UTF-8的變換後對應的int類型值  | 00000000 00000000 00000000 00000xxx    (范圍是0~7)

2字節 UTF-8的變換後對應的int類型值  | 00000000 00000000 00000000 0000110x    (范圍是12~13)

3字節 UTF-8的變換後對應的int類型值  | 00000000 00000000 00000000 00001110    (范圍是14)

4字節 UTF-8的變換後對應的int類型值  | 00000000 00000000 00000000 00001111    (范圍是15)

為什麼會是這樣呢?

我們以“2字節 UTF-8的通用格式”來說明。

它的通用格式是 “110xxxxx 10xxxxxx”,我們在操作時,只會操作第1個字節,即只會操作“110xxxxx”

(a.1) 在執行 c = (int) bytearr[count] & 0xff; 時,首先將 bytearr[count] 轉換成int。

“110xxxxx”

轉成int類型之後,變成

“11111111 11111111 11111111 110xxxxx”

因為“110xxxxx”是負數(第1為是1),所以轉換成int類型時多出來的位補1。

(a.2) 接著 c = (int) bytearr[count] & 0xff; 中,會將 “轉換成int類型後的bytearr[count]” 與 “0xff”進行 邏輯與(即&) 操作。結果如下:

“00000000 00000000 00000000 110xxxxx”

(a.3) 執行 c>>4 時,會將上面的結果左移4位。得到的結果如下:

“00000000 00000000 00000000 0000110x”

(b) 上面的理解之後,swicth (c>>4) { ... } 其中的省略號部分就相當容易理解了。

我們還是以“2字節 UTF-8的通用格式”來說明。

它會執行 case 12 和 case 13;源碼如下:

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));

(b.1) 由於這種情況對應的UTF-8數據是“2字節”的,因此,執行count+2;直接跳過2個字節。

(b.2) 由於chararr的元素是字符類型,而一個字符正好占2個字節;因為正好將(((c & 0x1F) << 6) | (char2 & 0x3F)); 的結果轉換成char,然後保存在chararr數組中。

第6步,將字符數組轉換成String字符串,並返回。代碼如下:

return new String(chararr, 0, chararr_count);

示例代碼

關於DataInputStream中API的詳細用法,參考示例代碼(DataInputStreamTest.java):

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.lang.SecurityException;
     
/**
 * DataInputStream 和 DataOutputStream測試程序
 *
 * @author skywang
 */
public class DataInputStreamTest {
     
    private static final int LEN = 5;
     
    public static void main(String[] args) {
        // 測試DataOutputStream,將數據寫入到輸出流中。
        testDataOutputStream() ;
        // 測試DataInputStream,從上面的輸出流結果中讀取數據。
        testDataInputStream() ;
    }
     
    /**
     * DataOutputStream的API測試函數
     */
    private static void testDataOutputStream() {
     
        try {
            File file = new File("file.txt");
            DataOutputStream out =
                  new DataOutputStream(
                      new FileOutputStream(file));
     
            out.writeBoolean(true);
            out.writeByte((byte)0x41);
            out.writeChar((char)0x4243);
            out.writeShort((short)0x4445);
            out.writeInt(0x12345678);
            out.writeLong(0x0FEDCBA987654321L);
     
            out.writeUTF("abcdefghijklmnopqrstuvwxyz嚴12");
     
            out.close();
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (SecurityException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
    }
    /**
     * DataInputStream的API測試函數
     */
    private static void testDataInputStream() {
     
        try {
            File file = new File("file.txt");
            DataInputStream in =
                  new DataInputStream(
                      new FileInputStream(file));
     
            System.out.printf("byteToHexString(0x8F):0x%s\n", byteToHexString((byte)0x8F));
            System.out.printf("charToHexString(0x8FCF):0x%s\n", charToHexString((char)0x8FCF));
     
            System.out.printf("readBoolean():%s\n", in.readBoolean());
            System.out.printf("readByte():0x%s\n", byteToHexString(in.readByte()));
            System.out.printf("readChar():0x%s\n", charToHexString(in.readChar()));
            System.out.printf("readShort():0x%s\n", shortToHexString(in.readShort()));
            System.out.printf("readInt():0x%s\n", Integer.toHexString(in.readInt()));
            System.out.printf("readLong():0x%s\n", Long.toHexString(in.readLong()));
            System.out.printf("readUTF():%s\n", in.readUTF());
     
            in.close();
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (SecurityException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
    }
     
    // 打印byte對應的16進制的字符串
    private static String byteToHexString(byte val) {
        return Integer.toHexString(val & 0xff);
    }
     
    // 打印char對應的16進制的字符串
    private static String charToHexString(char val) {
        return Integer.toHexString(val);
    }
     
    // 打印short對應的16進制的字符串
    private static String shortToHexString(short val) {
        return Integer.toHexString(val & 0xffff);
    }
}

運行結果:

byteToHexString(0x8F):0x8f

charToHexString(0x8FCF):0x8fcf

readBoolean():true

readByte():0x41

readChar():0x4243

readShort():0x4445

readInt():0x12345678

readLong():0xfedcba987654321

readUTF():abcdefghijklmnopqrstuvwxyz嚴12

結果說明:

(01) 查看file.txt文本。16進制的數據顯示如下:

001f 對應的int值是31。它表示的含義是後面的UTF-8數據的長度。字符串“abcdefghijklmnopqrstuvwxyz嚴12”中字母“ab...xyz”的長度是26,“嚴”對應的UTF-8數據長度是3;“12”長度是2。總的長度=26+3+2=31。

(02) 返回byte對應的16進制的字符串

源碼如下:

private static String byteToHexString(byte val) {

return Integer.toHexString(val & 0xff);

}

想想為什麼代碼是:

return Integer.toHexString(val & 0xff);

而不是

return Integer.toHexString(val);

我們先看看 byteToHexString((byte)0x8F); 在上面兩種情況下的輸出結果。

return Integer.toHexString(val & 0xff); 對應的輸出是“0xffffff8f”

return Integer.toHexString(val); 對應的輸出是“0x8f”

為什麼會這樣呢?

原因其實很簡單,就是“byte類型轉換成int類型”導致的問題。

byte類型的0x8F是一個負數,它對應的2進制是10001111;將一個負數的byte轉換成int類型時,執行的是有符號轉型(新增位都填充符號位的數字)。0x8F的符號位是1,因為將它轉換成int時,填充“1”;轉型後的結果(2進制)是11111111 11111111 11111111 10001111,對應的16進制為0xffffff8f。

因為當我們執行Integer.toHexString(val);時,返回的就是0xffffff8f。

在Integer.toHexString(val & 0xff)中,相當於0xffffff8f & 0xff,得到的結果是0x8f。

(03) 返回char和short對應的16進制的字符串

“返回char對應的16進制的字符串”對應的源碼如下:

private static String charToHexString(char val) {

return Integer.toHexString(val);

}

“返回short對應的16進制的字符串”對應源碼如下:

private static String shortToHexString(short val) {

return Integer.toHexString(val & 0xffff);

}

比較上面的兩個函數,為什麼一個是 “val” ,而另一個是 “val & 0xffff”?

通過(02)的分析,我們類似的推出為什麼 “返回short對應的16進制的字符串” 要執行“val & 0xffff”。

但是,為什麼 “返回char對應的16進制的字符串” 要執行 “val” 即可。原因也很簡單,java中char是無符號類型,占兩個字節。將char轉換為int類型,執行的是無符號轉型,新增為都填充0。

來源:http://www.cnblogs.com/skywang12345/p/io_14.html

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved