Heim > Java > Java-Tutorial > Hauptteil

如何通过JAVA NIO直接缓冲区拷贝文件

WBOY
Freigeben: 2023-04-19 10:01:02
nach vorne
1156 人浏览过

通过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();
      }
    }
  }
Nach dem Login kopieren

以上是如何通过JAVA NIO直接缓冲区拷贝文件的详细内容。更多信息请关注PHP中文网其他相关文章!

Verwandte Etiketten:
Quelle:yisu.com
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!