集册 Java实例教程 使用FileChannel和直接ByteBuffer复制文件

使用FileChannel和直接ByteBuffer复制文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

533
使用FileChannel和直接ByteBuffer复制文件
/**
来 自 时   代     Java  公  众  号 - nowjava.com
**/

import java.io.IOException;

import java.nio.ByteBuffer;

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");

    int bufferSizeKB = 4;

    int bufferSize = bufferSizeKB * 1024;

    System.out.println("Using FileChannel and direct buffer ...");

    try (FileChannel fileChannel_from = (FileChannel.open(copy_from,

        EnumSet.of(StandardOpenOption.READ)));// 来 自 时代Java公众号 - nowjava.com

        FileChannel fileChannel_to = (FileChannel

            .open(copy_to, EnumSet.of(StandardOpenOption.CREATE_NEW,

                StandardOpenOption.WRITE)))) {

      ByteBuffer bytebuffer = ByteBuffer.allocateDirect(bufferSize);

      int bytesCount;

      
展开阅读全文