歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 如何使用Java合並多個文件

如何使用Java合並多個文件

日期:2017/3/1 10:23:34   编辑:Linux編程

如何使用Java合並多個文件:

  1. import static java.lang.System.out;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.nio.ByteBuffer;
  6. import java.nio.channels.FileChannel;
  7. import java.util.Arrays;
  8. public class test {
  9. public static final int BUFSIZE = 1024 * 8;
  10. public static void mergeFiles(String outFile, String[] files) {
  11. FileChannel outChannel = null;
  12. out.println("Merge " + Arrays.toString(files) + " into " + outFile);
  13. try {
  14. outChannel = new FileOutputStream(outFile).getChannel();
  15. for(String f : files){
  16. FileChannel fc = new FileInputStream(f).getChannel();
  17. ByteBuffer bb = ByteBuffer.allocate(BUFSIZE);
  18. while(fc.read(bb) != -1){
  19. bb.flip();
  20. outChannel.write(bb);
  21. bb.clear();
  22. }
  23. fc.close();
  24. }
  25. out.println("Merged!! ");
  26. } catch (IOException ioe) {
  27. ioe.printStackTrace();
  28. } finally {
  29. try {if (outChannel != null) {outChannel.close();}} catch (IOException ignore) {}
  30. }
  31. }
  32. public static void main(String[] args) {
  33. mergeFiles("D:/output.txt", new String[]{"D:/in_1.txt", "D:/in_2.txt", "D:/in_3.txt"});
  34. }
  35. }
Copyright © Linux教程網 All Rights Reserved