>  기사  >  Java  >  JAVA NIO 버퍼에서 직접 파일을 복사하는 방법

JAVA NIO 버퍼에서 직접 파일을 복사하는 방법

WBOY
WBOY앞으로
2023-04-19 10:01:021233검색

JAVA NIO

/**
   * 通过JAVA NIO 直接缓冲区拷贝文件(内存映射文件)
   *
   * @param sourcePath 源文件路径
   * @param targetPath 目标文件路径
   */
  public static void copyFileByChannelBufferd(String sourcePath, String targetPath) {
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    try {
      //获取通道,StandardOpenOption.READ表示可读,StandardOpenOption.WRITE表示可写,StandardOpenOption.CREATE表示可以创建
      inChannel = FileChannel.open(Paths.get(sourcePath), StandardOpenOption.READ);
      outChannel = FileChannel.open(Paths.get(targetPath), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);

      //创建内存映射文件
      MappedByteBuffer inMapped = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
      MappedByteBuffer outMapped = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());

      //直接操作内存映射文件
      byte[] buf = new byte[inMapped.limit()];
      inMapped.get(buf);
      outMapped.put(buf);

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //关闭流
      try {
        if (outChannel != null) {
          outChannel.close();
        }
        if (inChannel != null) {
          inChannel.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
를 통해 버퍼에서 직접 파일 복사

위 내용은 JAVA NIO 버퍼에서 직접 파일을 복사하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제