Home > Java > javaTutorial > Java implementation of file copy: operation using character stream

Java implementation of file copy: operation using character stream

WBOY
Release: 2023-05-06 17:04:08
forward
1205 people have browsed it

File copying through character stream

Only text files can be copied using character stream

  /**
   * 通过字符流实现文件的拷贝
   *
   * @param sourcePath 源文件路径
   * @param targetPath 目标文件路径
   */
  public static void copyFileByReaderAndWriter(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();
    }

    FileReader in = null;
    FileWriter out = null;
    try {
      //字符输入流和字符输出流
      in = new FileReader(source);
      out = new FileWriter(target);

      char[] c = new char[1024];
      int temp = 0;
      //每次读取1024个字符
      while ((temp = in.read(c)) != -1) {
        //输出到文件
        out.write(c, 0, temp);
      }
    } catch (IOException 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 Java implementation of file copy: operation using character stream. 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