首先请查看一下JavaAPI,可以看到InputStream读取流有三个方法,分别为read(),read(byte[] b),read(byte[] b, int off, int len)。其中read()方法是一次读取一个字节,鬼都知道效率是非常低的。所以最好是使用后面两个方法。
例如以下代码是使用read(byte[] b)方法来完成的:[java]
package com.gaoxueping;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ReadStr {
public ReadStr() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
try{
File file = new File("F:\\123.txt");
FileInputStream fin = new FileInputStream(file);
byte[] filebt = readStream(fin);
System.out.println(filebt.length);
}catch(Exception e){
e.printStackTrace();
}
}
private static byte[] readStream(InputStream inStream) throws IOException{
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();
}
}[/java]