工作的时候用到的一些方法,在这里记录一下。
public class GetFileList {
private static ArrayList<File> fileList = new ArrayList<File>();
public static void main(String[] args) throws IOException {
String dir = "D:\\testFile\\temp1";
String dir2 = "D:\\testFile\\temp2";
//File targetFile = new File("D:\\testFile\\temp2");
String file_postfix_regex = ".txt";
ArrayList<File> matchesFiles = getFileList(dir,file_postfix_regex);
// 遍历获取到的文件
for (File matchesFile : matchesFiles) {
if (matchesFile.isFile()){
copyFile(matchesFile,new File(dir2+File.separator+matchesFile.getName()));
}
if (matchesFile.isDirectory()){
// 复制目录
String sourceDir = dir + File.separator + matchesFile.getName();
String targetDir = dir2 + File.separator + matchesFile.getName();
copyDirectiory(sourceDir,targetDir);
}
}
}
public static ArrayList<File> getFileList(String filePath,String file_postfix_regex){
File file = new File(filePath);
Pattern pattern = Pattern.compile(file_postfix_regex);
return getFileList(new File(filePath),pattern);
}
// 递归获取文件
private static ArrayList<File> getFileList(File file,Pattern pattern){
if(!file.exists()){
System.err.println(file + " don't exists.");
System.exit(1);
}
String fileName = file.getName();
if(file.isFile()){
Matcher matcher = pattern.matcher(fileName);
if(matcher.find()){
fileList.add(file);
}
}else if(file.isDirectory()){
File[] filesInDirectory = file.listFiles();
int length = filesInDirectory.length;
for(int i = 0 ; i < length ; i ++){
getFileList(filesInDirectory[i],pattern);
}
}
return fileList;
}
// 复制文件
public static void copyFile(File sourceFile, File targetFile) throws IOException {
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);
// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
//关闭流
inBuff.close();
outBuff.close();
output.close();
input.close();
}
// 复制文件夹
public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
// 新建目标目录
(new File(targetDir)).mkdirs();
// 获取源文件夹当前下的文件或目录
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile = file[i];
// 目标文件
File targetFile = new
File(new File(targetDir).getAbsolutePath()
+ File.separator + file[i].getName());
copyFile(sourceFile, targetFile);
}
if (file[i].isDirectory()) {
// 准备复制的源文件夹
String dir1 = sourceDir + File.separator + file[i].getName();
// 准备复制的目标文件夹
String dir2 = targetDir + File.separator + file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}
}