Java大文件高效分片、合并实战

本文介绍如何在Java中高效地对大文件进行分片和合并操作,适用于处理因文件过大而需分割上传的场景。
摘要由CSDN通过智能技术生成

Java大文件高效分片、合并实战

工作中有时候会遇到文件需要分片的应用场景,比如文件太大需要切割成多份文件上传等。
下面就跟着我一起开始吧

package com.chow.spirngbootdemo;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * @author Herman  Email: dg_chow@163.com
 * @date 2017-7-31 14:35
 */
public class MultipartUploadSender {
   

    public static final int BUF_SIZE = 1024 * 1204;
    public static final long MULTIPART_SIZE = 200 * 1024 * 1024;

    public static void main(String[] args) {
   

        String sourceFile = "D:\\MyProjects\\docker.zip";
        String targetPath = "D:\\MyProjects\\";
        String newFilePath = "D:\\MyProjects\\aaa.zip";
        // 分片开始-方式1
        long current = System.currentTimeMillis();
        MultipartUploadSender.fileSpilt(sourceFile, targetPath, MULTIPART_SIZE);
        System.out.println("普通IO方式用时(毫秒):" + (System.currentTimeMillis() - current));
        // 分片开始-方式2
        long current2 = System.currentTimeMillis();
        List<String> fileNames = MultipartUploadSender.fileSpiltWithNio(sourceFile, targetPath, MULTIPART_SIZE);
        System.out.println("NIO方式用时(毫秒):" + (System.currentTimeMillis() - current2));
        // 开始合并
        File[] fileList = FileFilter(targetPath, fileNames);
        mergeFileWithNio(fileList, newFilePath);
    }

    /**
     * 普通IO分片方式
     *
     * @param sourceFile    要分片的文件
     * @param targetPath    输出路径
     * @param multipartSize 文件被切割的大小,单位:byte
     *                      <p>
     *                      model各个参数详解
     *                      r 代表以只读方式打开指定文件
     *                      rw 以读写方式打开指定文件
     *                      rws 读写方式打开,并对内容或元数据都同步写入底层存储设备
     *                      rwd 读写方式打开,对文件内容的更新同步更新至底层存储设备
     */

    public static List<String> fileSpilt(String sourceFile, String targetPath, long multipartSize) {
   
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        List<String> fileNames = new LinkedList<>();
        try {
   
            RandomAccessFile raf = new RandomAccessFile
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值