利用ByteArrayInputStream、ByteArrayInputStream、FileInputStream、FileOutputStream优化文件的拷贝

ByteArrayInputStream、ByteArrayInputStream(字节数组流):可以把字节数组转化为流
FileInputStream、FileOutputStream (文件字节流):可以通过字节数组进行读写
二者可以配合使用

方法一,FileToByteArray()
这个方法首先根据FileInputStream把文件读到字节数组byte[]中,然后ByteArrayOutputStream会把含有数据的字节数组 byte[]写到字节内部维护的缓冲流中,最后利用toByteArray()方法,将数据整个变成一个byte[]。前面的FileInputStream虽然也是利用了字节数组,但是它所使用的字节数组只是把不断的利用字节数组把数据塞到里面去,可能重复了许多次,直到while循环不 成立。在事先不知道文件大小的情况下没办法把文件变成一个字节数组byte[]。

方法二,ByteArrayToFile()
这个方法恰恰相反,先是利用ByteArrayInputStream把byte[]字节数组数据读出来,将读出来的数据放入到事先定义好大小的字节数组,然后再把字节数组通过FileOutputStream类的write方法写到磁盘中去。

package IObase;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * 字节数组流与文件字节流
 * 1 选择源
 * 2 选择流
 * 3 搬运操作
 * 4 关流
 */
public class IOTest8 {
   
	
	public static void 
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
要将ByteArrayInputStream转换为FileInputStream,你可以使用以下步骤: 1. 创建一个临时文件,以便将ByteArrayInputStream中的数据写入磁盘。 2. 使用FileOutputStreamByteArrayInputStream中的数据写入临时文件。 3. 使用FileInputStream打开临时文件,以便进行进一步的操作。 下面是一个示例代码,展示了如何执行这些步骤: ```java import java.io.*; public class ByteArrayToFileInputStream { public static void main(String[] args) { ByteArrayInputStream byteArrayInputStream = null; FileOutputStream fileOutputStream = null; FileInputStream fileInputStream = null; try { // 创建一个示例的ByteArrayInputStream byte[] byteArray = "Hello, World!".getBytes(); byteArrayInputStream = new ByteArrayInputStream(byteArray); // 创建一个临时文件 File tempFile = File.createTempFile("temp", null); // 将ByteArrayInputStream中的数据写入临时文件 fileOutputStream = new FileOutputStream(tempFile); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = byteArrayInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, bytesRead); } // 打开临时文件作为FileInputStream fileInputStream = new FileInputStream(tempFile); // 在这里可以使用fileInputStream进行进一步的操作... } catch (IOException e) { e.printStackTrace(); } finally { try { if (byteArrayInputStream != null) { byteArrayInputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } if (fileInputStream != null) { fileInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 请注意,这只是一个示例代码,你可以根据你的具体需求进行修改和适应。另外,记得在不再需要临时文件时删除它。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值