寫個複製指定目錄下指定格式檔案到指定目錄下的方法
package com.test1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyTest {
private static final String frompath="C://Users/test.txt";
private static final String topath="D://Users/";
public static void main(String[] args) throws Exception {
File file = new File(frompath);
filter(file);
System.out.println("複製完成");
}
/**
* 篩選檔案
* @param file
* @throws Exception
*/
private static void filter(File file) throws Exception {
if(file.isDirectory()){
File []filelist=file.listFiles();
for (File f : filelist) {
filter(f);
}
}else{
String name = file.getName();
int len = name.length();
if(".txt".equals(name.substring(len-4))){
System.out.println("正在複製"+name+"....");
copyFile(file,new File(topath,name));
System.out.println("複製完成");
}
}
}
/**
* 複製檔案的方法
* @param frompath
* @param topath
* @throws Exception
*/
private static void copyFile(File frompath, File topath) throws Exception {
// TODO Auto-generated method stub
FileInputStream fis =new FileInputStream(frompath);
FileOutputStream fos = new FileOutputStream(topath);
byte [] b =new byte[1024];
int len;
while((len=fis.read(b))!=-1){
fos.write(b, 0, len);
}
fis.close();
fos.close();
}
}