RandomAccessFile 文件切片和合并

package com.lzw.flieslice;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 *  文件切片和文件合并
 */
public class FileSlice {

    // 文件合并
    private void fileComposite(String destDir) throws Exception {
        // 找到所有的文件切片
        Path path = Paths.get(destDir);
        List<Path> pathList = Files.list(path).sorted((o1, o2) -> {
            String f1 = o1.toString();
            String f2 = o2.toString();
            String f1Name = f1.substring(f1.lastIndexOf("\\") + 1, f1.lastIndexOf("."));
            String f2Name = f2.substring(f2.lastIndexOf("\\") + 1, f2.lastIndexOf("."));
            return Integer.parseInt(f1Name) - Integer.parseInt(f2Name);
        }).collect(Collectors.toList()); // 其实这个地方要做排序操作
        RandomAccessFile newFile = new RandomAccessFile(destDir + "test.rar", "rw");
        // 遍历所有的文件
        long position = 0;
        for (Path fp : pathList) {
            // 读取文件中的内容
            File file = fp.toFile();
            System.out.println(file.getName());
            RandomAccessFile accessFile = new RandomAccessFile(file, "r");
            FileChannel fileChannel = accessFile.getChannel();
            long fileSize = fileChannel.size();
            byte[] bs = new byte[(int) fileSize];
            accessFile.read(bs);
            newFile.seek(position);
            newFile.write(bs);
            position += fileSize;
            fileChannel.close();
        }
        newFile.close();
    }

    // 文件切割,每个文件分片大小为 1mb
    private void fileSlice(String srcPath, String destDir, long sliceSize) throws Exception {
        RandomAccessFile file = new RandomAccessFile(srcPath, "rw");
        // 获取文件大小
        long size = file.getChannel().size();

        long indexSeek = 0;

        int fileIndex = 1;

        while (size > 0) {
            // 文件slice size
            if (size < sliceSize) {
                sliceSize = size;
            }
            byte[] sliceByte = new byte[(int) sliceSize];
            file.seek(indexSeek);
            file.read(sliceByte);
            indexSeek = file.getChannel().position();
            size = size - sliceSize;
            // 保存切片文件
            RandomAccessFile newFile = new RandomAccessFile(destDir + fileIndex + ".rar", "rw");
            newFile.write(sliceByte);
            newFile.close();
            fileIndex ++;
        }

        file.close();
    }

    public static void main(String[] args) throws Exception {
        String srcPath = "D:/test/test.rar";
        String destDir = "D:/test/slice/";
        long sliceSize = 1024 * 1024 * 10; // 每个分片大小

        FileSlice fileSlice = new FileSlice();
        fileSlice.fileSlice(srcPath, destDir, sliceSize);
        fileSlice.fileComposite(destDir);
    }
}

 

posted @ 2023-05-04 10:47  文所未闻  阅读(211)  评论(0编辑  收藏  举报