博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
拆分文件_文件拆分与合并
阅读量:1545 次
发布时间:2019-04-21

本文共 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

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

转载地址:http://xfzcy.baihongyu.com/

你可能感兴趣的文章
19c删除spatial组件ORA-28014: cannot drop administrative user or role
查看>>
oracle快速查找阻塞会话
查看>>
rufus制作u盘启动
查看>>
dell r340安装window和linux
查看>>
OGG-14036 Schema is required for heartbeattable : gg_heartbeat.
查看>>
OGG-05673 CSN-based duplicate suppression is disabled because there is no checkpoint table for this
查看>>
19c多租户ogg微服务命令行查看参考
查看>>
如何配置GOLDENGATE的数据库日志策略、TRAILFILE策略以及存在坑
查看>>
建库时在全局名称中添加了xxx.com,后续如何去掉?
查看>>
WRI$_ADV_OBJECTS表过大,导致PDB的SYSAUX表空间不足
查看>>
oracle查看带末尾下划线的表名和字段名
查看>>
nfs挂接命令参考
查看>>
oracle一体机(exdata)创建ACFS文件系统
查看>>
xshell起图形界面后,鼠标点击不了
查看>>
limit资源限制ulimit 详解
查看>>
MAX_STRING_SIZE controls the maximum size of VARCHAR2, NVARCHAR2, and RAW data types in SQL.
查看>>
How to estimate RMAN incremental backup size using block change tracking file (Doc ID 1938079.1)
查看>>
rman备份分配指定操作
查看>>
rman备份指定备份集对应文件
查看>>
ffmpeg分割mp4视频方便快速
查看>>