package 拷贝文件;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFile {
public static void main(String[] args) {
String path ="d:/file";
Execute e = new Execute();
e.exe(path);
}
}
//执行部分
class Execute{
public void exe(String s){
File f = new File(s);
//查找目标文件
f.list(new FilenameFilter(){
//过滤文件
public boolean accept(File dir, String name) {
//找出所要找的文件 //判断是否是.txt结尾的文件
if(name.endsWith(".txt")){
//获取的path,将\转换成/
String path = dir.getPath().replace("\\", "/");
System.out.println(path);
//copy部分
File f1 = new File(path+"/"+name);
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(f1);
os = new FileOutputStream("f:/mm/"+name);//将读入的文件,写入到这个文件中
byte [] b = new byte[1024];
int len = 0;
while((len=is.read(b))!=-1){
os.write(b);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
//关闭流
is.close();os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
return false;
}
});
//判断是否是文件夹,如果是文件则进入该文件
f.listFiles(new FileFilter(){
public boolean accept(File pathname) {
if(pathname.isDirectory()){
exe(pathname.getPath().replace("\\", "/"));
return true;
}
return false;
}
});
}
}