Java实现文件分割和文件合并实例
更新时间:2017年08月01日 08:50:55 作者:左世钰
本篇文章主要介绍了Java实现文件分割和文件合并实例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud)
(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun)
文件切割和文件合并这个问题困扰了我有一段时间了(超过一天没做粗来)。
找了好多博客,本来想转载一个来的 结果找不到了。很无奈。
只好自己贴代码上了。
当然我会尽力好好写注释的。
文件切割器:
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException, IOException { File sourceFile = new File("ping.mp3"); // System.out.println(sourceFile.exists()); Scanner scanner = new Scanner(System.in); int numberOfPieces = 1; //默认文件切割的数量 System.out.println("Enter:"); //提示输入 numberOfPieces = scanner.nextInt(); //输入 scanner.close(); //输入后就关闭 装完逼就跑一个道理 long fileLength = sourceFile.length() / numberOfPieces; //分一下每一个小文件的大小 byte[] b = new byte[1024]; //这个不解释 如果看不懂 就去看IO流去吧 RandomAccessFile raf1 = new RandomAccessFile(sourceFile, "r"); int len = -1; for(int i = 0; i < numberOfPieces; i++) { String name = sourceFile.getName() + "." + (i+1); File file = new File(name); file.createNewFile(); RandomAccessFile raf2 = new RandomAccessFile(file, "rw"); while((len = raf1.read(b)) != -1) { raf2.write(b, 0, len); //我觉的这样写比raf2.write(b);高明一些 if(raf2.length() > fileLength) //如果太大了就不在这个子文件写了 换下一个 break; } raf2.close(); } raf1.close(); } }
文件合并器:
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; //文件合并 ping.n public class Main { public static void main(String[] args) throws FileNotFoundException, IOException { File[] files = new File[10]; String name = "ping."; File file = new File("ping.mp3"); 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 < files.length; i++) { files[i] = new File(name + (i + 1)); //System.out.println(files[i].exists()); RandomAccessFile out = new RandomAccessFile(files[i], "rw"); while((len = out.read(bytes)) != -1) { in.write(bytes, 0, len); } out.close(); } in.close(); } }
文件合并器就不写注释了,因为这是一个逆过程。(懒癌附体)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。
相关文章
解决Spring配置文件中bean的property属性中的name出错问题
这篇文章主要介绍了解决Spring配置文件中bean的property属性中的name出错问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-07-07springboot webflux 过滤器(使用RouterFunction实现)
这篇文章主要介绍了springboot webflux 过滤器(使用RouterFunction实现),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-03-03SpringCloud?@RefreshScope刷新机制浅析
RefeshScope这个注解想必大家都用过,在微服务配置中心的场景下经常出现,他可以用来刷新Bean中的属性配置,那大家对他的实现原理了解吗?它为什么可以做到动态刷新呢2023-03-03
最新评论