Home > Java > javaTutorial > How to implement file copy through byte buffer stream in java

How to implement file copy through byte buffer stream in java

王林
Release: 2023-04-30 21:49:13
forward
1365 people have browsed it

File copying through byte buffer stream

/**
   * 通过字节缓冲流实现文件的拷贝
   *
   * @param sourcePath 源文件路径
   * @param targetPath 目标文件路径
   */
  public static void copyFileByBuffered(String sourcePath, String targetPath){
    //源文件路径
    File source = new File(sourcePath);
    //目标文件路径
    File target = new File(targetPath);

    //如果源文件不存在则不能拷贝
    if (!source.exists()) {
      return;
    }
    //如果目标文件目录不存在则创建
    if (!target.getParentFile().exists()) {
      target.getParentFile().mkdirs();
    }

    InputStream in = null;
    OutputStream out = null;
    try {
      //字节缓冲输入流和字节缓冲输出流
      in = new BufferedInputStream(new FileInputStream(source));
      out = new BufferedOutputStream(new FileOutputStream(target));

      byte[] b = new byte[1024];
      int temp = 0;
      //每次读取一个1024的字节数组
      while((temp = in.read(b)) != -1){
        //输出到文件
        out.write(b,0,temp);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      //关闭流
      try {
        if (in != null) {
          in.close();
        }
        if (out != null) {
          out.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Copy after login

The above is the detailed content of How to implement file copy through byte buffer stream in java. 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