File concatenation using channel transfer - Java File Path IO

Java examples for File Path IO:File Channel

Description

File concatenation using channel transfer

Demo Code

import java.io.FileInputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

public class Main {
  public static void main(String[] argv) throws Exception {
    String[] files = new String[] { "a.txt", "b.txt" };
    catFiles(Channels.newChannel(System.out), files);
  }/*from   www . j av a 2 s .c o m*/

  private static void catFiles(WritableByteChannel target, String[] files)
      throws Exception {
    for (int i = 0; i < files.length; i++) {
      FileInputStream fis = new FileInputStream(files[i]);
      FileChannel channel = fis.getChannel();

      channel.transferTo(0, channel.size(), target);

      channel.close();
      fis.close();
    }
  }

}

Related Tutorials