Copying Files with FileChannel.map() - Java File Path IO

Java examples for File Path IO:File Channel

Description

Copying Files with FileChannel.map()

Demo Code

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

public class Main {
  public static void main(String[] args) {
    Path copy_from = Paths
        .get("C:/folder1/folder2/folder3/videos/test.mp4");
    Path copy_to = Paths.get("C:/test.mp4");

    System.out.println("Using FileChannel.map method ...");
    try (FileChannel fileChannel_from = (FileChannel.open(copy_from,
        EnumSet.of(StandardOpenOption.READ)));
        FileChannel fileChannel_to = (FileChannel
            .open(copy_to, EnumSet.of(StandardOpenOption.CREATE_NEW,
                StandardOpenOption.WRITE)))) {

      MappedByteBuffer buffer = fileChannel_from.map(
          FileChannel.MapMode.READ_ONLY, 0, fileChannel_from.size());

      fileChannel_to.write(buffer);//from   w  w  w.j a v  a  2  s . c om
      buffer.clear();

    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials