FileChannel文件切片和合并Java(JavaFx)

package client.botpmsclient.util.fielCut;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @ Author J
 */
public class FileSlip {
    /**
     * file name
     */
    private static String FILENAME;

    /**
     * 5GB
     */
    private static final double FIFTYMBITSIZE5G = 5242880000D;

    /**
     * to eight slip
     */
    private static final int FILESLICPQUAN = 8;

    /**
     * path of file output
     */
    private static final String FILEOUPUTPATH = "C:\\Users\\Lara\\Desktop\\py\\fx\\";

    public static void fileToSlip(File fileGet) throws Exception {
        //chosen the file and file not eq none
        if (fileGet != null) {
            //file path
            String filePath = fileGet.getAbsolutePath();
            System.out.println("文件路径是:" + filePath);
            //file size
            long fileSize = fileGet.length();
            //file name
            FILENAME = fileGet.getName();
            //target path
            String targetPath = FILEOUPUTPATH + FILENAME;
            File tar = new File(targetPath);
            //if target file already existed
            if (tar.exists()) {
                //Alert confirmation
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setTitle(null);
                alert.setHeaderText(null);
                alert.setContentText("The File Already Existed,Sure?");
                Optional<ButtonType> conf = alert.showAndWait();
                // if No
                if (conf.get() != ButtonType.OK) {
                    //tar.deleteOnExit();
                    throw new RuntimeException("您取消了上传文件。");
                }
            }
            //when under five GB
            if (fileSize <= FIFTYMBITSIZE5G) {

                long starTime = System.currentTimeMillis();

                RandomAccessFile raf = new RandomAccessFile(fileGet, "r");
                //data block(slip) size
                long blockSize = fileSize / FILESLICPQUAN;
                if (fileSize % FILESLICPQUAN != 0) {
                    blockSize++;
                }
                List<File> fileList = new ArrayList<>();
                //slip file and save to disk
                for (int i = 0; i < FILESLICPQUAN; i++) {
                    try {
                        long start = i * blockSize;
                        //get the min one between fileSize and slipSize
                        long end = Math.min(start + blockSize, fileSize);
                        byte[] buff = new byte[(int) (end - start)];
                        //stand the start position of slip
                        raf.seek(start);
                        //read to cache
                        raf.read(buff);
                        String path = FILEOUPUTPATH + File.separator + i + ".temp";
                        FileOutputStream os = new FileOutputStream(path);
                        //write slip to
                        os.write(buff);
                        os.close();
                        fileList.add(new File(path));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                mergerFile(fileList, tar, starTime);
            } else {
                return;
            }
        }
    }

    //merge file
    public static void mergerFile(List<File> fileList, File tar, long startTime) {
        //get output
        new Thread(() -> {
            try (FileOutputStream os = new FileOutputStream(tar)) {
                //get the outPut Channel
                FileChannel osChannel = os.getChannel();
                //merge all the slips into a original file.now
                for (File file : fileList) {
                    //get input
                    try (FileInputStream is = new FileInputStream(file)) {
                        //get the Input Channel
                        FileChannel isChannel = is.getChannel();
                        //slip size
                        long count = isChannel.size();
                        //transfer data from isChannel to osChannel
                        isChannel.transferTo(0, count, osChannel);
                        System.out.println("slip size: " + count);
                        System.out.println("Files merged successfully into: " + tar.getAbsolutePath());
                    } catch (Exception x) {
                        tar.deleteOnExit();
                        x.printStackTrace();
                    }
                }

            } catch (Exception x) {
                tar.deleteOnExit();
                x.printStackTrace();
            } finally {
                int i = 0;
                for (File file1 : fileList) {
                    file1.deleteOnExit();
                    System.out.println("删除了Temp文件 " + i + ":" + file1.getName());
                    i++;
                }
            }
            System.out.println("总耗时:" + (System.currentTimeMillis() - startTime) + " ms");
        }).start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值