Maison  >  Article  >  Java  >  Comment copier des fichiers directement à partir du tampon JAVA NIO

Comment copier des fichiers directement à partir du tampon JAVA NIO

WBOY
WBOYavant
2023-04-19 10:01:021230parcourir

Copiez les fichiers directement depuis le tampon via 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();
      }
    }
  }

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer