java InputStream读取数据问题

首先请查看一下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]

Avatar photo

About Blackford

这是个最好的时代,这是个最坏的时代,这是个充满希望的春天,这是个令人绝望的冬天,我们前面什么都有,我们前面什么都没有。梦想,让我们一次次的走远,又一次次的回头,一个关于人生的梦想还在不断奔跑,带着喜悦和疼痛,不过一切才刚刚开始,并且直到今天也远远没有结束
This entry was posted in Java编程语言 and tagged , . Bookmark the permalink.

发表评论

电子邮件地址不会被公开。 必填项已用*标注