注意:1.打印流pw关闭前需进行判空,否则会报空指针异常
2.需用count接收递归调用时返回的count值,否则遍历子目录后返回的还是父目录的count值
public class TxtDemo {
public static void main(String[] args) {
System.out.println("txt文件的个数为 :" + countAndCopy(new File("e:\\demo"), new File("e:\\demo1\\b"),0));
}
/*
* 定义方法,获取指定目录下txt文件的个数
* 并将这些txt文件复制到自定义目录
*/
public static int countAndCopy(File src,File dest,int count) {
BufferedReader bfr = null;
PrintWriter pw = null;
try {
File[] fileArr = src.listFiles();
for(File f : fileArr) {
if(f.isDirectory()) {
//应设置count变量接收目录里面的count值并进行返回,否则遍历完子目录,返回父目录时,count值依旧是父目录里的count值
count = countAndCopy(f,dest,count);
}else {
if(f.getName().endsWith(".txt")) {
bfr = new BufferedReader(new FileReader(f));
pw = new PrintWriter(new FileWriter(dest.getAbsolutePath() + "\\" + f.getName()),true);
++count;
String line = null;
while((line = bfr.readLine()) != null) {
pw.println(line);
}
}
}
}
//注意应对打印流进行判空,否则遍历一个没有.txt文件的目录时会报NullPointerException
if(pw != null)
pw.close();
}catch(IOException ex) {
System.out.println(ex);
throw new RuntimeException("读写文件失败");
}finally {
try {
if(bfr != null)
bfr.close();
}catch(IOException ex) {
throw new RuntimeException("释放文件失败");
}
}
return count;
}
}