public class Demo_7 {
public static void main(String[] args) throws Exception {
System.out.println("请输入文件夹路径");
Scanner sc = new Scanner(System.in);
String as = sc.nextLine();
// 定义原文件夹
File sourceFolder = new File(as);
// 定义复制的文件夹
File destFolder = new File("D://java");
if (sourceFolder.isFile()) { // 判断是不是文件
System.out.println("您输入的有误");
} else if (!sourceFolder.exists()) {
System.out.println("您输入的指定文件夹不存在");
} else {
method(sourceFolder, destFolder);// 调用
}
}
public static void method(File sourceFolder, File destFolder)
throws Exception {
// 判断destFolder 存不存在
if (!destFolder.exists()) {
destFolder.mkdir();
}
// 获取原文件夹下所有文件 (夹)
File[] file = sourceFolder.listFiles();
// 遍历
for (File thisfile : file) {
if (thisfile.isDirectory()) {
method(thisfile, destFolder);// 递归调用
} else if (thisfile.getName().endsWith(".java")) {
method2(thisfile, destFolder);// 读写它
}
}
}
public static void method2(File thisfile, File destFolder) throws Exception {
// 创建字符输入流对象
FileReader reader = new FileReader(thisfile);
BufferedReader br = new BufferedReader(reader);
// 创建字符输出流对象
// 获取名字
File destFile = new File(destFolder, thisfile.getName());
FileWriter writer = new FileWriter(destFile);
BufferedWriter bw = new BufferedWriter(writer);
String asd = "";
while ((asd = br.readLine()) != null) {
bw.write(asd);
}
br.close();
bw.close();
}
}
|
|