查看系統(tǒng)后臺的源代碼時拧揽,看到下面一段:
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()方法是一次讀取一個字節(jié),效率很低馋嗜,所以一般都會使用后面兩個方法齐板,每次都讀取緩沖區(qū)的一整塊數(shù)據(jù)來提高讀取的速度。
一個小例子:
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()方法是一次
* 讀取一個字節(jié),效率很低
* @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();
}
}
}