拆分文件_文件拆分与合并
发布日期:2021-06-24 16:44:27
浏览次数:5
分类:技术文章
本文共 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月06日 14时04分17秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
写C# dll供Unity调用
2019-04-27
Linux制作run安装包
2019-04-27
一分钟学会C#解析XML
2019-04-27
unity AssetBundle的资源管理
2019-04-27
【转】Unity中HideInInspector和SerializeField一起使用
2019-04-27
单例模板类
2019-04-27
Unity与java相互调用
2019-04-27
android截屏代码
2019-04-27
unity NGUI图文混排
2019-04-27
Unity项目优化
2019-04-27
Unity3D Shader 入门
2019-04-27
C#用正则表达式去匹配被双引号包起来的中文
2019-04-27
lua table排序
2019-04-27
Unity发布的ios包在iphone上声音是从听筒里出来的问题
2019-04-27
UIScrollView复用节点示例
2019-04-27
Unity 5 AudioMixer
2019-04-27
Unity 代码混淆: CodeGuard的使用
2019-04-27
UGUI 列表循环使用
2019-04-27
使用命令行运行unity并执行某个静态函数(运用于命令行打包和批量打包)
2019-04-27