美文网首页Java技术文章
InputStream读取byte[]的方法

InputStream读取byte[]的方法

作者: lunabird | 来源:发表于2016-02-25 11:23 被阅读4911次

查看系统后台的源代码时,看到下面一段:

public void writeTo(OutputStream o)
        throws IOException
    {
        byte b[] = new byte[1024];
        for(int size = 0; (size = stream.read(b)) != -1;)
            o.write(b, 0, size);
    }

原来,InputStream读取流有三个方法,分别为read(),read(byte[] b),
read(byte[] b, int off, int len)。其中read()方法是一次读取一个字节,效率很低,所以一般都会使用后面两个方法,每次都读取缓冲区的一整块数据来提高读取的速度。
一个小例子:

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
/**
 * InputStream读取流有三个方法,分别为read(),read(byte[] b),
 * read(byte[] b, int off, int len)。其中read()方法是一次
 * 读取一个字节,效率很低
 * @author lunabird
 */
public class InputStreamTest {
    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while((len=inStream.read(buffer))!=-1){
            outStream.write(buffer,0,len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }
    public static void main(String[] args){
        try{
            File file = new File("E:\\proj\\docs\\temp\\zxing.jar");
            FileInputStream fin = new FileInputStream(file);
            byte[] filebt = readStream(fin);
            System.out.println(filebt.length);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

相关文章

网友评论

    本文标题:InputStream读取byte[]的方法

    本文链接:https://www.haomeiwen.com/subject/yybikttx.html