public class FindandCopy {
//查找文件
public static void findmethod(File file1,File file2,String findtype,String changetype) throws Exception{
if(!file1.exists()){
return ;
}else if(file1.isFile()){
//文件夾不存在就建立
if(!file2.exists()){
file2.mkdirs();
}
if(file1.getName().endsWith(findtype)){
copy(file1,file2,findtype,changetype);
}
}else if(file1.isDirectory()){
File[] files = file1.listFiles();
for(File f : files){
findmethod(f,new File(file2 + "\\" + file1.getName()),findtype,changetype);
}
}
}
//複製文件
public static void copy(File pathr,File pathw,String findtype,String changetype) throws Exception{
InputStream is = new FileInputStream(pathr);
OutputStream os = new FileOutputStream(pathw + "\\" + pathr.getName().replaceAll(findtype,changetype));
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(os);
//讀 寫 文件
byte[] b = new byte[1024];
int length = 0;
while((length = bis.read(b)) != -1){
bos.write(b,0,length);
bos.flush();
// bis.close();
// bos.close();
}
}
//刪除
public static void deletefile(File file){
if(!file.exists()){
return ;
}else if(file.isFile()){
file.delete();orm
}else if(file.isDirectory()){
File[] files = file.listFiles();
for(File f : files){
deletefile(f);
f.delete();get
//if(f.exists()){f.delete();}
}
file.delete();
}
}
}
it
------------io
Test 類form
public class Test extends FindandCopy{class
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("------------------複製與刪除------------------\n");
System.out.println("\t\t[1] 複製\n\t\t[2] 刪除\n\t\t[0] 退出\n請選擇操做:");
while(true){
int chose = sc.nextInt();
switch(chose){
case 1 :
System.out.println("請輸入要複製的位置(路徑)");
File f1 = new File(sc.next());
System.out.println("請輸入要拷貝到的位置(路徑)");
File f2 = new File(sc.next());
System.out.println("請輸入要複製前的文件後綴名");
String findtype = sc.next();
System.out.println("請輸入要拷貝後的文件後綴名");
String changetype = sc.next();
findmethod(f1,f2,findtype,changetype);
//打印出當前時間
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String time = sdf.format(new Date());
System.out.println(time);
break;
case 2 :
System.out.println("請輸入要刪除的位置(路徑)");
File deletefind = new File(sc.next());
deletefile(deletefind);
file
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String time1 = sdf1.format(new Date());
System.out.println(time1);
break;
case 0 :System.exit(0);
default:
}
}
}
}
im