java合并多个文件的实例代码

在本篇文章里小编给大家整理的是关于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) new file(fpaths[0]).renameto(new file(resultpath)); file[] files=new file[fpaths.length]; for (int i < fpaths.length; ++) files[i]=new file(fpaths[i]); (textutils.isempty(fpaths[i]) !files[i].exists() !files[i].isfile()) file resultfile=new file(resultpath); try int bufsize=1024; bufferedoutputstream outputstream=new bufferedoutputstream(new fileoutputstream(resultfile)); byte[] buffer=new byte[bufsize]; 0; bufferedinputstream inputstream=new bufferedinputstream(new fileinputstream(files[i])); 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 

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"); }

以上就是java如何合并多个文件的详细内容,感谢大家的学习和对html中文网的支持。

以上就是java合并多个文件的实例代码的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java