探究java IO之ByteArrayInputStream類

ByteArrayInputStream是使用字節數組做爲源的輸入流的一個實現。這個類有兩個構造函數,每一個構造函數都須要一個字節數組來提供數據源:java

ByteArrayInputStream(byte[] buf)
ByteArrayInputStream(byte[] buf, int offset, int length)

在此,buf是輸入源。第二個構造函數從字節數組的子集建立InputStream對象,這個數組子集從start指定的索引位置的字符開始,共length個字節。數組

close()方法 對ByteArrayInputStream對象沒有效果。因此,不須要爲ByteArrayInputStream對象調用close()方法,可是若是這麼作的話,也不會產生錯誤。函數

見下面一個例子:spa

package o1;

import java.io.ByteArrayInputStream;

public class ByteArrayInputStreamTest {
    public static void main(String[] args) {
        String str = "import java.io.ByteArrayInputStream;";
        try(ByteArrayInputStream b = new ByteArrayInputStream(str.getBytes(),7,29)){
            int n;
            while((n = b.read()) != -1){
                System.out.print((char)n);
            }
            System.out.println();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

ByteArrayInputStream實現了mark()reset()方法。然而,若是沒有調用mark()方法,那麼reset()方法會將流指針設置爲流的開頭——在這種狀況下,也就是設置爲傳遞給構造函數的字節數組的開頭。見下面兩個例子:指針

package o1;

import java.io.ByteArrayInputStream;

public class ByteArrayInputStreamTest2 {
    public static void main(String[] args) {
        String str = "import java.io.ByteArrayInputStream;";
        try(ByteArrayInputStream b = new ByteArrayInputStream(str.getBytes())){
            int n,m = 0;
            while((n = b.read()) != -1){
                char c = (char)n;
                System.out.print(c);
                if(c == ' ') {
                    b.mark(m);
                    break;
                }
                m++;
            }
            System.out.println();
            b.reset();
            while((n = b.read()) != -1){
                char c = (char)n;
                System.out.print(c);
            }
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

例2:code

package o1;

import java.io.ByteArrayInputStream;

public class ByteArrayInputStreamTest3 {
    public static void main(String[] args) {
        String str = "import java.io.ByteArrayInputStream;";
        try(ByteArrayInputStream b = new ByteArrayInputStream(str.getBytes())){
            int n,m =0;
            while((n = b.read()) != -1){
                char c = (char)n;
                System.out.print(c);
                if(m >= 6) {
                    //只有reset()方法調用,沒有mark()方法調用
                    b.reset();
                    m = 0;
                    System.out.println();
                    break;
                }
                m++;
            }
            while((n = b.read()) != -1){
                char c = (char)n;
                System.out.print(c);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
相關文章
相關標籤/搜索