在开发中经常需要操作FileInputStream流,但通常不是直接操作它,而是把它转化成一个InputStream流来操作。
在apache的commons包中有个org.apache.commons.io.IOUtils.toByteArray(InputStream);可以很方便的把一个FileInputStream转换成一个byte[]。
然后再利用ByteArrayInputStream,可以转换成InputStream流。
下面的代码就是根据org.apache.commons.io.IOUtils.toByteArray(InputStream input)的源码改写的一个方法:
public InputStream getInputStream(FileInputStream fileInput) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*4];
int n = -1;
InputStream inputStream = null;
try {
while ((n=fileInput.read(buffer)) != -1) {
baos.write(buffer, 0, n);
}
byte[] byteArray = baos.toByteArray();
inputStream = new ByteArrayInputStream(byteArray);
return inputStream;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
下面就对上面的方法作一些解释,为什么要把FileInputStream流转换成InputStream流,FIleInputStream是InputStream流的子类,在能用到父类的地方都可以被子类替换
那我们为什么还要费力的把FileInputStream流转换成InputStream流呢?我们获取的FileInputStream流一般都是通过这样的方法来获取的:
String path = "c:/hello.txt";
File file = new File(path);
FileInputStream fileInput = null;
fileInput = new FileInputStream(file);
这种方法获取的一般是硬盘文件上的一个指针,可能是直接操作硬盘上的文件效率低吧,或者是因为其他的原因,一般会把这个FileInputStream流转换为一个内存块中的输入流,即ByteArrayInputStream流来操作。