java中,mergeFiles方法实现多个文件内容合并

  首先,说一下我写这篇文章的目的:最近,领导分配一个任务给我,让我把多个文件中的编码进行一个一个执行,光一个文件夹里就有40多个文件,况且还是30多个文件,这样一个一个执行要浪费多少时间和精力。

  无奈,只能自己找点java方法,来减少工作量。

  所以,我打算将文件夹下所有文件的内容集中在一个文件内,可以一次执行完。

  特此,把我找来的方法与大家分享,但是这个并不是我的原创。

  首先:建立java项目的目录以及jar包(jre的内部包,无需自己查找)如下:

java方法实现将文件中的内容进行合并(第二个文件所有内容插在第一个文件的末尾,依次类比),方法如下:

15 public class test {
16     public static final int BUFSIZE = 1024 * 8;
17     @SuppressWarnings("resource")
    //outFile合并后的内容要存入的文件,files目标文件集(文件合并的方法) 18 public static void mergeFiles(String outFile, String[] files) { 19 FileChannel outChannel = null; 20 out.println("Merge " + Arrays.toString(files) + " into " + outFile); 21 try { 22 outChannel = new FileOutputStream(outFile).getChannel(); 23 for (String f : files) { 24 Charset charset = Charset.forName("utf-8"); 25 CharsetDecoder chdecoder = charset.newDecoder(); 26 CharsetEncoder chencoder = charset.newEncoder(); 27 FileChannel fc = new FileInputStream(f).getChannel(); 28 ByteBuffer bb = ByteBuffer.allocate(BUFSIZE); 29 CharBuffer charBuffer = chdecoder.decode(bb); 30 ByteBuffer nbuBuffer = chencoder.encode(charBuffer); 31 while (fc.read(nbuBuffer) != -1) { 32 bb.flip(); 33 nbuBuffer.flip(); 34 outChannel.write(nbuBuffer); 35 bb.clear(); 36 nbuBuffer.clear(); 37 } 38 fc.close(); 39 } 40 out.println("Merged!! "); 41 } catch (IOException ioe) { 42 ioe.printStackTrace(); 43 } finally { 44 try { 45 if (outChannel != null) { 46 outChannel.close(); 47 } 48 } catch (IOException ignore) { 49 } 50 } 51 } 52 53 public static void main(String[] args) { //main方法 54 String sourceDir = "G:\\org\\zy141230\\"; 55 File[] file = (new File(sourceDir)).listFiles(); //获取文件夹sourceDir下所有文件 56 //String[] result=new String[]{file.toString()}; 57 //file=file.toString(); 58 ArrayList<String> list = new ArrayList<String>(); //String类型的数组 59 String [] strs = new String[file.length]; //可以定义动态的String数组 60 for (int i = 0; i < file.length; i++) { 61 // list.add(sourceDir + file[i].getName()); 62 strs[i] = sourceDir + file[i].getName(); //将信息存入文件的String数组 63 } 64 /*for (int i = 0; i < strs.length; i++) { //验证,数组能否正常输出 65 //System.out.println(strs[i]); 66 }*/ 67 // list.toArray(); 68 mergeFiles("G:\\finish\\zy141230\\606_177052856.lst", strs);  //将strs中文件集合到G:\\finish\\zy141230\\606_177052856.lst文件中 69 } 70 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值