package cn.it.text; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter; /*
* 2.获取指定目录及子目录下所有txt文件的个数,并将这些txt文件复制到D盘下任意目录
*/
public class Text2 {
public static int num = 0; public static void main(String[] args) throws Exception {
File file = new File("f:\\a");
getTxt(file);
System.out.println("复制完成!");
System.out.println("txt文件的个数是:"+num); } public static void getTxt(File file) throws Exception { // 判断传入的文件是否存在
if (file.exists()) {
File[] fileArr = file.listFiles();
for (File f : fileArr) {
// 判断是否是文件夹
if (f.isDirectory()) {
getTxt(f);
} // 不是文件夹的话,判断是否是txt
if (f.getName().endsWith("txt")) {
num += 1;
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File("f:\\c", f.getName())));
int len;
while ((len = in.read()) != -1) {
out.write(len);
} in.close();
out.close();
} }
} }
}