java实现大文件的分割与合并
最近遇到一个问题,某网盘上传文件时,文件大小超过了4个G ,不能上传,所以就想到了利用的java的IO流,将文件分割成多个小文件,上传到网盘上,等到需要用的时候,下载下来然后再进行文件的合并就可以了。
这里以分割一个8.85M的PDF文件为例,分割成每个大小为1M的文件,分割文件的大小,只需修改size即可,代码如下:
1.文件的分割
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public static void main(String[] args) throws IOException { //要分割出来的文件的大小 int size = 1024 * 1024 * 1 ; //1M BufferedInputStream in = new BufferedInputStream( new FileInputStream( new File( "D:\\zzy\\aaaa\\fileSplit\\java.pdf" ))); int len = - 1 ; for ( int i = 0 ; i < 9 ; i++) { //8.85M的文件分割成8个1M的,和一个0.85M的 File file = new File( "D:\\zzy\\aaaa\\fileSplit\\" + i + "temp.temp" ); //分割的文件格式可以随便设置,只要文件合并时名称一致即可 FileOutputStream outputStream = new FileOutputStream(file); BufferedOutputStream out = new BufferedOutputStream(outputStream); int count = 0 ; byte [] bt = new byte [ 1024 * 1024 ]; //每次读取1M,数组大小不能太大,会内存溢出,通过目标文件大小size判断一下 while ((len = in.read(bt)) != - 1 ) { out.write(bt, 0 , len); count += len; if (count>=size) { break ; //每次读取1M,然后写入到文件中 } } out.flush(); out.close(); outputStream.close(); System.out.println( "文件已完成:" + file.getName()); } System.out.println( "文件已完成分割====" ); } |
2.文件的合并
public static void main(String[] args) throws IOException { //文件合并 BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream( new File( "D:\\zzy\\aaaa\\fileSplit\\java(merge).pdf" ))); for ( int i = 0 ; i < 9 ; i++) { //9个文件合并成8.85M的文件 File file = new File( "D:\\zzy\\aaaa\\fileSplit\\" + i + "temp.temp" ); FileInputStream inputStream = new FileInputStream(file); BufferedInputStream in = new BufferedInputStream(inputStream); int len = - 1 ; byte [] bt = new byte [ 1024 * 1024 ]; //每次读取1M,数组大小不能太大,会内存溢出 while ((len = in.read(bt)) != - 1 ) { out.write(bt, 0 , len); } in.close(); inputStream.close(); out.flush(); System.out.println( "文件已完成:" + file.getName()); } System.out.println( "文件已完成合并====" ); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构