含读写及替换字符的复制文件操作

本文介绍了一个Java工具类,用于实现文件夹的完整复制,并在复制过程中替换指定字符。该工具支持递归处理子目录,适用于批量修改文件内容的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class ChangeFile {
 /**
  * 复制整个文件夹内容,并替换所有文件中的";"
  *
  * @param oldPath
  *            String 原文件路径 如:e:/b/
  * @param newPath
  *            String 复制后路径 如:e:/a/
  */
 public void copyFolder(String oldPath, String newPath) {

  try {
   (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
   File a = new File(oldPath);
   String[] file = a.list();
   File temp = null;
   for (int i = 0; i < file.length; i++) {
    if (oldPath.endsWith(File.separator)) {
     temp = new File(oldPath + file[i]);
    } else {
     temp = new File(oldPath + File.separator + file[i]);
    }

    if (temp.isFile()) {

     this.writeFile(this.readerFile(temp.toString()), newPath
       + "/" + (temp.getName()).toString());
    }
    if (temp.isDirectory()) {// 如果是子文件夹
     copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
    }
   }
   System.out.println("复制文件夹操作 成功执行");
  } catch (Exception e) {
   System.out.println("复制整个文件夹内容操作出错");
   e.printStackTrace();

  }
 }

 public String readerFile(String filePath) {
  String a = "";
  File f = new File(filePath);
  if (f.exists()) {
   try {
    // 下为读取文件
    BufferedReader raf = new BufferedReader(
      new FileReader(filePath));
    char[] buf = new char[1024 * 5];
    int len = raf.read(buf);
    a = new String(buf, 0, len);
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return a.replaceAll(";", " ");
 }


       public String readerFile(String filePath) {
  StringBuffer sb = new StringBuffer();
  File f = new File(filePath);
  if (f.exists()) {
   try {
    // 下为读取文件
    BufferedReader raf = new BufferedReader(
      new FileReader(filePath));
    String line = "";
    while ((line = raf.readLine()) != null) {

     if (line.trim().length() > 0) {

      sb.append(line + "/r/n");
     }
    }
    raf.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  String b = sb.toString();
  b = b.substring(0, b.length() - 2);
  return b.replaceAll(";", " ");
 }


 public static void writeFile(String content, String filePath) {
  BufferedWriter bw = null;
  try {
   bw = new BufferedWriter(new FileWriter(filePath));
   bw.write(content);
   bw.flush();
  } catch (Exception e) {
   e.printStackTrace();

  } finally {
   if (bw != null) {
    try {
     bw.close();
    } catch (Exception ex) {

    }
    bw = null;
   }
  }
 }

 public static void main(String[] args) {
  ChangeFile a = new ChangeFile();
  a.copyFolder("e:/b/", "e:/a/");
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值