如何使用Java合并多个文件


如何使用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. }  

相关内容