首頁 > Java > java教程 > 主體

如何透過JAVA NIO直接緩衝區拷貝文件

WBOY
發布: 2023-04-19 10:01:02
轉載
1157 人瀏覽過

透過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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!