Java:如何实现文件与数组的相互转换?

在这篇文章中,我将向您展示如何将文件转换为字节数组,然后再将字节数组转换为文件。
要将文件转换为字节数组,请使用ByteArrayOutputStream类。此类实现输出流,在该流中,数据被写入字节数组。缓冲区随着数据写入自动增长。可以使用toByteArray()和toString()检索数据。
要将字节数组转换回原始文件,请使用FileOutputStream类。文件输出流是用于将数据写入文件或FileDescriptor的输出流。
以下代码已经过全面测试。
import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.logging.Level;import java.util.logging.Logger;
public class genFile {

public static void main(String[] args) throws FileNotFoundException, IOException {
    File file = new File("java.pdf");

    FileInputStream fis = new FileInputStream(file);
    //System.out.println(file.exists() + "!!");
    //InputStream in = resource.openStream();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    try {
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
            bos.write(buf, 0, readNum); //no doubt here is 0
            //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
            System.out.println("read " + readNum + " bytes,");
        }
    } catch (IOException ex) {
        Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
    }
    byte[] bytes = bos.toByteArray();

    //below is the different part
    File someFile = new File("java2.pdf");
    FileOutputStream fos = new FileOutputStream(someFile);
    fos.write(bytes);
    fos.flush();
    fos.close();
}}

最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值