拆分文件_文件拆分与合并
发布日期:2021-06-24 16:44:27 浏览次数:4 分类:技术文章

本文共 1650 字,大约阅读时间需要 5 分钟。

项目中遇到大文件上传,前端会将大文件切分,后台进行文件合并。为实现这个功能,先实现文件合并功能。

我选择使用RandomAccessFile,相比FileInputStream。RandomAccessFile多了很多功能,非常方便,具体可查看API。

拆分文件代码

/** * 拆分文件 * * @param f */public static void split(File f) throws IOException {​    // 切分为100K大小的文件    long fileLength = 1024 * 100;​    RandomAccessFile src = new RandomAccessFile(f, "r");    int numberOfPieces = (int) (src.length() / fileLength) + 1;    int len = -1;    byte[] b = new byte[1024];    for (int i = 0; i < numberOfPieces; i++) {​        String name = "src/test/resources/file/" + f.getName() + "." + (i + 1);        File file = new File(name);        file.createNewFile();        RandomAccessFile dest = new RandomAccessFile(file, "rw");        while ((len = src.read(b)) != -1) {            dest.write(b, 0, len);            //如果太大了就不在这个子文件写了 换下一个            if (dest.length() > fileLength) {                break;            }        }        dest.close();    }    src.close();}

效果

a4f8b19cca028caf23b43862b1043346.png

可见生成了三个小文件

文件合并代码

/** * 文件合并 * @throws IOException */public static void merge() throws IOException {        int length = 3;    String name = "src/test/resources/file/src.pdf.";    File file = new File("src/test/resources/file/new.pdf");    file.createNewFile();    RandomAccessFile in = new RandomAccessFile(file, "rw");    in.setLength(0);    in.seek(0);    byte[] bytes = new byte[1024];    int len = -1;    for (int i = 0; i < length; i++) {        File src = new File(name + (i + 1));        RandomAccessFile out = new RandomAccessFile(src, "rw");        while ((len = out.read(bytes)) != -1) {            in.write(bytes, 0, len);        }        out.close();    }    in.close();}
a866a8be8124535acf3745568c9b2460.png

看一下文件大小,没问题

a9209f470972fafb38690cfa7e62794b.png

打开文件试一下,没问题,可以正常打开

转载地址:https://blog.csdn.net/weixin_33921444/article/details/112574275 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:开发优势_小程序开发优势好处有哪些
下一篇:5v 温度范围_±10V/±5V/0-5V/0-10V/0-20mA转PWM隔离模块GMU00x

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月11日 00时20分01秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章