简单练习了下
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/*
* 计算指定路径下所有txt文件包括子文件夹里的.txt文件的个数然后将所有的.txt文件复制到D盘下任意目录;
* */
public class Test {
public static void main(String[] args) throws IOException {
File file = getFile();
File target = getFile();
int txtFileNum = fileCopy(file,target);
System.out.println(txtFileNum);
}
private static int fileCopy(File file,File target) throws IOException {
int num = 0;
File[] files = file.listFiles();
for (File f : files) {
if(f.isFile() && f.getName().endsWith(".txt")){
num ++;
FileReader fr = new FileReader(f);
FileWriter fw = new FileWriter(target.getAbsolutePath()+"\\"+f.getName());
char[] ch = new char[1024];
int len;
while((len = fr.read(ch)) != -1){
fw.write(ch, 0, len);
}
fr.close();
fw.close();
}else{
num = num + fileCopy(f,target);
}
}
return num;
}
private static File getFile() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个文件夹路径:");
while(true){
String path = sc.nextLine();
File file = new File(path);
if(!file.exists()){
System.out.println("输入的路径不存在,请重新输入");
} else if(file.isFile()){
System.out.println("输入的是文件路径,请重新输入文件夹路径:");
} else {
return file;
}
}
}
}
|