时间:2020-10-16 13:01:47 | 栏目:JAVA代码 | 点击:次
在实际项目中,在处理较大的文件时,常常将文件拆分为多个子文件进行处理,最后再合并这些子文件。下面就为各位介绍下Java中合并多个文件的方法。
Java中合并子文件最容易想到的就是利用BufferedStream进行读写。
具体的实现方式如下,代码很详细,供各位参考学习。
1、首先创建mergeFiles方法,接收字符串数组和字符串参数,并完成文件合并功能
public static boolean mergeFiles(String[] fpaths, String resultPath) { if (fpaths == null || fpaths.length < 1 || TextUtils.isEmpty(resultPath)) { return false; } if (fpaths.length == 1) { return new File(fpaths[0]).renameTo(new File(resultPath)); } File[] files = new File[fpaths.length]; for (int i = 0; i < fpaths.length; i ++) { files[i] = new File(fpaths[i]); if (TextUtils.isEmpty(fpaths[i]) || !files[i].exists() || !files[i].isFile()) { return false; } } File resultFile = new File(resultPath); try { int bufSize = 1024; BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(resultFile)); byte[] buffer = new byte[bufSize]; for (int i = 0; i < fpaths.length; i ++) { BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(files[i])); int readcount; while ((readcount = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, readcount); } inputStream.close(); } outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } for (int i = 0; i < fpaths.length; i ++) { files[i].delete(); } return true; }
2、然后在main函数中对mergeFiles方法进行调用,使用时传入多个文件的地址数组,并传入输出文件地址即可。
public static void main(String[] args) { mergeFiles(new String[]{"D:/in_1.txt", "D:/in_2.txt", "D:/in_3.txt"}, "D:/output.txt"); }