探究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();
        }
    }
}
相关文章
相关标签/搜索