手机版
你好,游客 登录 注册
背景:
阅读新闻

如何使用Java合并多个文件

[日期:2012-05-06] 来源:Linux社区  作者:huoyin [字体:大 中 小]

如何使用Java合并多个文件:

  1. import static java.lang.System.out;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.nio.ByteBuffer;  
  7. import java.nio.channels.FileChannel;  
  8. import java.util.Arrays;  
  9.   
  10.   
  11. public class test {  
  12.       
  13.     public static final int BUFSIZE = 1024 * 8;  
  14.       
  15.     public static void mergeFiles(String outFile, String[] files) {  
  16.         FileChannel outChannel = null;  
  17.         out.println("Merge " + Arrays.toString(files) + " into " + outFile);  
  18.         try {  
  19.             outChannel = new FileOutputStream(outFile).getChannel();  
  20.             for(String f : files){  
  21.                 FileChannel fc = new FileInputStream(f).getChannel();   
  22.                 ByteBuffer bb = ByteBuffer.allocate(BUFSIZE);  
  23.                 while(fc.read(bb) != -1){  
  24.                     bb.flip();  
  25.                     outChannel.write(bb);  
  26.                     bb.clear();  
  27.                 }  
  28.                 fc.close();  
  29.             }  
  30.             out.println("Merged!! ");  
  31.         } catch (IOException ioe) {  
  32.             ioe.printStackTrace();  
  33.         } finally {  
  34.             try {if (outChannel != null) {outChannel.close();}} catch (IOException ignore) {}  
  35.         }  
  36.     }  
  37.       
  38.     public static void main(String[] args) {  
  39.         mergeFiles("D:/output.txt", new String[]{"D:/in_1.txt", "D:/in_2.txt", "D:/in_3.txt"});  
  40.     }  
  41. }  
linux
相关资讯       Java教程 
本文评论   查看全部评论 (1)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款
第 1 楼
* 匿名 发表于 2013/8/7 15:21:00
合并文件后乱码了!