Java实现文件分割与合并

Java实现文件分割与合并

我们在上传一些文件时,由于文件过大,单一线程进行上传过于耗时。

我们需要对文件进行分割,将大文件分割成若干个文件进行上传,再有文件系统终端进行合并。

简单模拟实现一下吧!

主要使用到的类

RandomAccessFile

它可以灵活读写文件,类似指针操作。

具体实现逻辑夹杂在代码内

package com.highjet.demo.file;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/*
*
* 文件切割
*
* */
public class FileCutUtil {
    public static void main(String[] args) throws Exception {
        String filepath="C:\\Users\\acer\\Desktop\\test\\test.jar";

        File file=new File(filepath);

        cut(file,filepath,10);


        //合并文件  (文件合并输出路径 ,文件分片输入路径 ,分片数量)
        mergeFile("C:\\Users\\acer\\Desktop\\test\\out.jar","C:\\Users\\acer\\Desktop\\test\\test.jar",10);

        deleteTempFile("C:\\Users\\acer\\Desktop\\test\\test.jar",10);

    }

    public static void cut(File file,String filepath,int count) {

        //获取当前文件大小 只读模式
        RandomAccessFile in = null;
        long length=0;
        try {
            in = new RandomAccessFile(file, "r");
            length = in.length();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("当前文件长度:"+length);

        //文件切片后的长度
        long maxSize = length / count;
        //初始化偏移量
        long offSet = 0L;


        //普通分片处理
        for (int i = 0; i < count - 1; i++) {
            long begin = offSet;
            long end = (i + 1) * maxSize;

            offSet = WriteFile(filepath, i, begin, end);
        }
        //终分片 处理
        if (length - offSet > 0) {
            WriteFile(filepath, count-1, offSet, length);
        }
        //需要关闭文件流

    }

    /*
    * 写入文件
    * file 源文件
    * index 分割编码
    * begin 开始指针位置
    * end 结束指针位置
    * */
    public static long WriteFile(String file,int index,long begin,long end){
        String a=getStrBeforeFileExtension(file);
        long endPointer = 0L;
        try {
            //读取被分割 目标文件
            RandomAccessFile in = new RandomAccessFile(new File(file), "r");
            //读写模式开启 分片文件temp
            RandomAccessFile out = new RandomAccessFile(new File(a + "_" + index + ".tmp"), "rw");

            //作为缓存 的字节数组
            byte[] tempByteArray = new byte[1024];
            int n = 0;

            //从指定位置读取文件字节
            in.seek(begin);
            //判断文件流读取的边界
            while(in.getFilePointer() <= end && (n = in.read(tempByteArray)) != -1){
                //写入temp分片文件内
                out.write(tempByteArray, 0, n);
            }
            //定义当前读取文件的指针
            endPointer = in.getFilePointer();
            //关闭输入流
            in.close();
            //关闭输出流
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return endPointer;
    }

    /*
     * 文件合并
     * file 输出文件地址
     * tempFile 暂存文件地址
     * tempCount 分片文件总数
     * */
    public static void mergeFile(String file,String tempFile,int tempCount) {
        String nameAndPath=getStrBeforeFileExtension(tempFile);

        RandomAccessFile raf = null;
        RandomAccessFile reader=null;
        try {
            //申明随机读取文件RandomAccessFile
            raf = new RandomAccessFile(new File(file), "rw");
            //开始合并文件,对应切片的二进制文件
            for (int i = 0; i < tempCount; i++) {
                //读取切片文件
                reader = new RandomAccessFile(new File(nameAndPath + "_" + i + ".tmp"), "r");
                byte[] tempByteArray = new byte[1024];
                int n = 0;

                while ((n = reader.read(tempByteArray)) != -1) {
                    raf.write(tempByteArray, 0, n);
                }
                //解除暂存文件  占用  才能删除 temp文件
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(raf!=null){
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
    //获取扩展名前字符串
    public static String getStrBeforeFileExtension(String originalFileName) {

        return originalFileName.substring(0,originalFileName.lastIndexOf("."));
    }
    //删除temp文件
    public static void deleteTempFile(String path,int count){
        String nameAndPath=getStrBeforeFileExtension(path);

        for (int index=0;index<count;index++){
            File tempFile = new File(nameAndPath + "_" + index + ".tmp");
            System.out.println(tempFile.getAbsoluteFile());

            if (tempFile.isFile() && tempFile.exists())
            {
                tempFile.delete();
            }
        }

    }


}

具体效果图

这些jar包也是能正常执行的。


版权声明:本文为weixin_42477252原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。