拆分文件_文件拆分与合并
发布日期: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();}
效果
可见生成了三个小文件
文件合并代码
/** * 文件合并 * @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();}
看一下文件大小,没问题
打开文件试一下,没问题,可以正常打开
转载地址:https://blog.csdn.net/weixin_33921444/article/details/112574275 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月11日 00时20分01秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Druid连接池实现自定义场景的多数据库的连接
2019-04-27
PL/SQL数据库管理工具的使用
2019-04-27
带你玩转属于自己的spring-boot-starter系列(一)
2019-04-27
带你玩转属于自己自己的spring-boot-starter系列(二)
2019-04-27
FTP文件管理项目(本地云)项目日报(二)
2019-04-27
FTP文件管理项目(本地云)项目日报(七)
2019-04-27
什么是服务熔断?
2019-04-27
服务器压力过大?CPU打满?我来帮你快速检查Linux服务器性能
2019-04-27
C++面经总结之《Effective C++》(一)
2019-04-27
C++面经总结之《Effective C++》(二)
2019-04-27
这是什么“虎狼之词”啊!!!程序员的健康问题,看一线老中医怎么说!!!
2019-04-27
打开我的收藏夹 -- Python数据分析杂谈
2019-04-27
linux shell — 6.初识 EXT2 文件系统
2019-04-27
python - 【用户、商品】【购买、浏览】数据处理
2019-04-27
python - sql + pandas 与 sqlite 结合
2019-04-27
python - 使用sql 分析(06 - 15)国内各省GDP
2019-04-27
python - 抓取汇率数据分析美元和欧元对RMB的变化曲线
2019-04-27
python 数据科学 - 【回归分析】 ☞ 线性回归(2)
2019-04-27