首頁  >  文章  >  Java  >  java如何透過字元緩衝流拷貝文件

java如何透過字元緩衝流拷貝文件

WBOY
WBOY轉載
2023-05-02 08:28:06855瀏覽

透過字元緩衝流拷貝檔案

字元緩衝流只能讀取文字檔案

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

    BufferedReader in = null;
    BufferedWriter out = null;

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

      //读取文件(每次读取一行)
      String temp = null;
      while((temp = in.readLine()) != null){
        //输出到文件
        out.write(temp);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      //关闭流
      try {
        if (in != null) {
          in.close();
        }
        if (out != null) {
          out.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

以上是java如何透過字元緩衝流拷貝文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除