IO流分割文件

public class Demo_02 {
    /*
    写一个方法,将feige.exe文件分割为每份1MB大小的若干份,
    存储在一个temp的文件夹中(每份文件名自己定义),
    1.temp 2.temp...然后再写一个方法,将这若干份合并为一个文件.
    (注意路径,没有的文件要创建or自行补充代码)
     */
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("D:\\练习\\feige.exe");
        String path = "D:\\练习\\temp";
        //这里最好先获取源文件大小,然后按照想要的大小判断分成几份,再进行读写
        byte[] bytes = new byte[1024*1024];
        int len = -1;
        int name = 0;
        while ((len = fis.read(bytes)) != -1){ //读取字节数组大小的数据,没有数据返回-1
            //将数据写入到指定文件中,没有文件会自动创建,有会刷新
            FileOutputStream fos = new FileOutputStream(new File(path,++name+".temp.txt"));
            //写入指定长度数据、有效数据
            fos.write(bytes,0,len);
            //流只能用一次,每次都要创建关闭
            fos.close();
        }
        fis.close();
        File file = new File(path);
        //合并文件
        mergeFile(file);
    }
    //也可以将分割代码封装起来,自行尝试
    public static void mergeFile(File file) throws IOException {
        File[] files = file.listFiles();//获取当前文件夹的所有子文件集合
        FileOutputStream fos = new FileOutputStream("D:\\练习\\test\\feige1.exe");
        byte[] bytes = new byte[8192];
        int len;
        for (File f:files){//每个文件数据写入到一个文件中
            FileInputStream fis = new FileInputStream(f);//每次创建新的流
            while ((len = fis.read(bytes)) != -1){
               fos.write(bytes,0,len);
            }
            fis.close();
        }
        fos.close();
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值