Home > Java > javaTutorial > body text

File copying using Java NIO indirect buffers

WBOY
Release: 2023-05-07 11:19:07
forward
994 people have browsed it

Copy files through JAVA NIO indirect buffer

  /**
   * 通过JAVA NIO 非直接缓冲区拷贝文件
   *
   * @param sourcePath 源文件路径
   * @param targetPath 目标文件路径
   */
  public static void copyFileByChannel(String sourcePath, String targetPath) {
    FileChannel outChannel = null;
    FileChannel inChannel = null;

    FileInputStream fis = null;
    FileOutputStream fos = null;

    try {
      fis = new FileInputStream(sourcePath);
      fos = new FileOutputStream(targetPath);

      //获取通道
      inChannel = fis.getChannel();
      outChannel = fos.getChannel();

      //分配指定大小的缓冲区
      ByteBuffer buf = ByteBuffer.allocate(1024);

      while (inChannel.read(buf) != -1) {
        //转换为读取数据模式
        buf.flip();
        //写入到磁盘
        outChannel.write(buf);
        //清空缓冲区
        buf.clear();
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      //关闭流
      try {
        if (outChannel != null) {
          outChannel.close();
        }
        if (inChannel != null) {
          inChannel.close();
        }
        if (fis != null) {
          fis.close();
        }
        if (fos != null) {
          fos.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Copy after login

The above is the detailed content of File copying using Java NIO indirect buffers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!