美文网首页
Java File文件的分割与合并

Java File文件的分割与合并

作者: 有梦想的狼 | 来源:发表于2020-10-15 14:53 被阅读0次

准备工作

定义一个定时器,监听分割文件和合并文件的耗时。

public class Times {

    @FunctionalInterface
    public interface Block{
        abstract void execute();
    }
    
    public static void timeConsuming(Block block) {
        System.out.println("开始-------------------");
        long startTime = System.currentTimeMillis();
        block.execute();
        long endTime = System.currentTimeMillis();
        System.out.println("结束-------------------");
        long second = (endTime - startTime) / 1000;
        System.out.println("共耗时:" + second + "秒");
    }
}

分割文件

  1. 获取需要分割文件的存储路径
    String separator = File.separator;
    String userHomePath = System.getProperty("user.home");
    String originalDirectoryPath = userHomePath + separator + "Downloads";
    String fileNameString = "GMA71.zip";
    
  2. 进行文件的分割
    /**
     * 文件分割
     * @param targetFilePath 目标文件路劲
     * @throws Exception
     * 默认分割后每个文件最大为1MB
     */
    private static void fileSplit(String targetFilePath) throws Exception {
        fileSplit(targetFilePath, ".part", 1024 * 1024);
    }
    /**
     * 文件分割
     * @param targetFilePath 目标文件路劲
     * @param eachFileMaxSize 分割后每个文件的最大大小,默认是1MB
     * @throws Exception 
     */
    private static void fileSplit(String targetFilePath, String fileExtensionNameString,int eachFileMaxSize) throws Exception {
        assert(eachFileMaxSize > 0) : "eachFileMaxSize不能小于等于0";
        if (targetFilePath == null || targetFilePath.length() == 0) {
            throw new Exception("目标路径不能为空");
        }
        // 创建目标文件
        File targetFile = new File(targetFilePath);
        if (targetFile.exists()) {
            try (
                    /*
                     * 初始化输入流
                     * 先初始化一个文件输入流
                     * 为节省性能损耗,再初始化缓存输入流
                     */
                    BufferedInputStream bIS = new BufferedInputStream(
                            new FileInputStream(targetFile));){
                
                String separator = File.separator;
                // 分割后的文件存储目录
                String splitFolderPath = targetFile.getParent() + separator + "分割";
                
                // 从缓存输入流中,一次性最多读取多少个字节
                byte[] b = new byte[eachFileMaxSize];
                // 读取的字节长度
                int len = 0;
                //循环个数
                int count = 0;
                //获取文件的名字,包含扩展名
                String name = targetFile.getName();
                int index = name.lastIndexOf(".");
                name = name.substring(0, index) + fileExtensionNameString;
                
                //从缓存输入流中读取数据
                while ((len = bIS.read(b)) != -1) {
                    // 初始化分割后的文件
                    File splitFile = new File(splitFolderPath + separator + ++count +  "_" + name);
                    // 获取分割后的文件所在的目录
                    File parentFile = splitFile.getParentFile();
                    // 判断目录是否存在
                    if (!parentFile.exists()) {
                        // 创建所有目录
                        if (parentFile.mkdirs()) {
                            System.out.println(parentFile.getName() + "文件夹创建成功");
                        }
                    }
                    // 判断分割后的文件是否存在
                    if (!splitFile.exists()) {
                        // 创建分割后的文件
                        if (splitFile.createNewFile()) {
                            System.out.println(splitFile.getName() + "文件创建成功");
                        }
                    }
                    
                    try (
                            // 初始化文件输出流
                            BufferedOutputStream bOS = new BufferedOutputStream(new FileOutputStream(splitFile));){
                        // 往分割后的文件中写入数据
                        bOS.write(b, 0, len);
                        bOS.flush();
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }               
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }else {
            throw new Exception("目标文件不存在");
        }
    }
    
  3. 打印结果如下: image.png

合并文件

  1. 获取需要合并的文件所在的目录
    String separator = File.separator;
    String userHomePath = System.getProperty("user.home");
    String originalDirectoryPath = userHomePath + separator + "Downloads";
    String fileNameString = "RPReplay_Final1602630844.mp4";
    String parentFileNameString = "分割";
    
  2. 进行文件合并
    /**
     * 文件合并
     * @param targetParentFilePath 合并文件所在目录
     * @param fileNameString 合并后的文件名
     * @throws Exception
     */
    private static void fileMerge(String targetParentFilePath, String fileNameString) throws Exception {
        if (targetParentFilePath == null || targetParentFilePath.length() == 0) {
            throw new Exception("目标路径不能为空");
        }
        
        File parentFile = new File(targetParentFilePath);
        if (!parentFile.exists()) {
            throw new Exception("目录不存在");
        }
        
        File[] listFiles = parentFile.listFiles();
        // 目录中是否有文件
        if (listFiles.length == 0) {
            return;
        }
        // 进行排序
        Arrays.sort(listFiles, (File o1, File o2) -> {
            // TODO Auto-generated method stub
            String name1 = o1.getName().split("_")[0];
            String name2 = o2.getName().split("_")[0];
            int num1 = Integer.parseInt(name1);
            int num2 = Integer.parseInt(name2);
            return num1 - num2;
        });
        
        String mergePathString = parentFile.getParent() + File.separator + "合并" + File.separator + fileNameString;
        File mergeFile = new File(mergePathString);
        if (!mergeFile.getParentFile().exists()) {
            if (mergeFile.getParentFile().mkdirs()) {
                System.out.println(mergeFile.getParentFile().getName() + "文件夹创建成功");
            }
        }
        if (!mergeFile.exists()) {
            if (!mergeFile.createNewFile()) {
                System.out.println(mergeFile.getName() + "文件创建成功");
            }
        }
        
        // 初始化输入流集合
        Vector<InputStream> vector = new Vector<InputStream>();
        for (File file : listFiles) {
            vector.add(new FileInputStream(file));
        }
        
        try (
                // 初始化集合输入流
                SequenceInputStream sequenceInputStream = new SequenceInputStream(vector.elements());
                BufferedOutputStream boStream = new BufferedOutputStream(new FileOutputStream(mergeFile));){
            byte[] b = new byte[1024 * 1024];
            int len = -1;
            while ((len = sequenceInputStream.read(b)) != -1) {
                boStream.write(b, 0, len);;
            }
            boStream.flush();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    
  3. 在main函数中调用该静态方法
    Times.timeConsuming(() -> {
      try {
        fileMerge(originalDirectoryPath + separator + parentFileNameString, fileNameString);
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    });
    
  4. 打印结果如下: image.png

相关文章

  • Java File文件的分割与合并

    准备工作 定义一个定时器,监听分割文件和合并文件的耗时。 分割文件 获取需要分割文件的存储路径String sep...

  • 文件的分割与合并

    我极限了,这个程序讲不清。我每一步都有分析,仔细看程序设计这样的程序,都是一步一步的走,感觉少什么再完善修改前面的...

  • IO流之合并流

    SequenceInputStream合并流 可将多个读取流合并,通常用于大文件切割后的合并; 文件的分割 文件的合并

  • NDK开发基础③增量更新之服务器端生成差分包

    接续上篇NDK开发基础②文件加密解密与分割合并 前情提要 IO操作 , 一直在开发中占据很大比重 , 在Java中...

  • 文件分割与合并 Split

    ubuntu: 切分 切分成500M一个文件,以zxq_开头 split -b 500m zxq_生成的文件形如...

  • 2020-10-31 Java File和IO流

    java中与文件相关的操作封装在File类中File file = new File(path);初始化file....

  • JAVA 中的 IO 流

    File 类的使用 java.io.File 类:文件和文件目录路径的抽象表示形式,与平台无关 File 能新建、...

  • Linux下二进制文件的分割与合并

    Linux下二进制文件的分割与合并 dd的作用是转换和拷贝文件,我们可以利用它来分割文件,相关的选项如下: if=...

  • Java IO流笔记

    File类 功能与作用 java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关 File能新建、...

  • paste

    paste -d : file1 file2 > file3, 把两个文件的内容按列合并,与cat命令直接将不同文...

网友评论

      本文标题:Java File文件的分割与合并

      本文链接:https://www.haomeiwen.com/subject/thbwyktx.html