Java BufferedInputStream read()方法

java.io.BufferedInputStream.read(byte[] b, int off, int len) 从给定的偏移量开始,它将指定的字节输入流中的字节读入指定的字节数组。

1 语法

public int read(byte[] b, int off, int len)

2 参数

b:要填充的字节数组。

off:从偏移量开始存储。

len:要读取的字节数。

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.BufferedInputStream.read(byte[] b, int off, int len)方法的例子
 */
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;

public class Demo {
    public static void main(String[] args) throws Exception {
        InputStream inStream = null;
        BufferedInputStream bis = null;

        try {
            // open input stream test.txt for reading purpose.
            inStream = new FileInputStream("d:/test.txt");

            // input stream is converted to buffered input stream
            bis = new BufferedInputStream(inStream);

            // read number of bytes available
            int numByte = bis.available();

            // byte array declared
            byte[] buf = new byte[numByte];

            // read byte into buf , starts at offset 2, 3 bytes to read
            bis.read(buf, 2, 3);

            // for each byte in buf
            for (byte b : buf) {
                System.out.println((char)b+": " + b);
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            // releases any system resources associated with the stream
            if(inStream!=null)
                inStream.close();
            if(bis!=null)
                bis.close();
        }
    }
}

假设test.txt内容如下:

ABCDE

输出结果为:

 : 0
 : 0
A: 65
B: 66
C: 67

热门文章

优秀文章