IO文件分割与合并附代码

IO:文件分割与合并:附代码

package ff.learn.iow09;

import java.io.*;

/**
 * 3.写一个方法,将一个文件分割为每份1MB大小的若干份,存储在一个temp的文件夹中,
 *  *   然后再写一个方法,将这若干份合并为一个文件.
 */
public class homework03 {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\丿维美\\Desktop\\设计阶段课设报告.doc");
        division(file);
        /*File file1 = new File("C:\\Users\\丿维美\\Desktop\\problam\\temp");
        join(file1);*/
    }
     /**
     *
     * @param file 要分割的文件
     */
    public static void division(File file) throws IOException {
        if (file != null && file.exists()) { //检测形参的存在性
            File file1 = new File("C:\\Users\\丿维美\\Desktop\\problam\\temp1");
            if (file1 == null || !file1.exists()) { //检测分割文件后存入的路径
                file1.mkdir();
            }
            long size = file.length();//文件大小
            long f = 1024 * 1024;//限制每份文件大小为1Mb
            long t = size % f == 0 ? size / f : size / f + 1;//文件份数
            //构建输入流
            FileInputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int o = 0;
            int num = 0;//记录每次写文件的大小
            for (int i = 0; i < t; i++) {
                //分割每份文件生成一个对象
                FileOutputStream out = new FileOutputStream("C:\\Users\\丿维美\\Desktop\\problam\\temp1\\" + (i + 1) + ".temp1");
                while ((o = in.read(b)) != -1) {
                    out.write(b, 0, o);
                    num += o;   //每写一次,num数值增加
                    if (num >= f) { //如果超过限制大小,结束当前本次写文件操作并且num清零
                        num = 0;
                        break;
                    }
                }
            }
        }
    }

    /**
     *
     * @param file 要合并的文件
     * @throws IOException
     */
    public static void join(File file) throws IOException {
        if(file!=null&&file.exists()){//检测传入文件的合法性
          File[] f =  file.listFiles();
          int num = 0;
          FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\丿维美\\Desktop\\problam\\设计阶段课设报告.doc");//合并后文件的路径及名字
            for (int i = 0; i < f.length; i++) {
                num++;
                FileInputStream in = new FileInputStream("C:\\Users\\丿维美\\Desktop\\problam\\temp\\"+num+".temp");//需要合并的文件路径及文件名
                byte[] v = new byte[1024];
                int o = 0;
                while ((o=in.read(v))!=-1){
                    fileOutputStream.write(v,0,o);
                }
                in.close();
            }
            fileOutputStream.close();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值