把FileInputStream转换成InputStream

在开发中经常需要操作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流来操作。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值