package com.zyliao.common.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* java遍历文件夹并复制文件到指定目录
* Package: com.zyliao.common.file
* File: CopyFolder.java
* @Author: liaozhiyong Date: 2015-1-23
* Copyright @ 2015
*/
public class CopyFolder {
// 允许复制的文件类型
// public static String[] filterFile = { ".java", ".xml", ".xdl",
// ".properties", ".sql", ".jupiter", ".wsdl" };
public static String[] filterFile = { ".jpg", ".gif" };
private long total = 0l;
public static void main(String[] args) throws Exception {
// Scanner scanner = new Scanner(System.in);
// String answer = null;
// do {
// System.out.println("Enter src folder:");
// String srcStr = scanner.next();
// String destStr;
// System.out.println("Now enter dest folder:");
// destStr = scanner.next();
// File src = new File(srcStr);
// File des = new File(destStr);
// new CopyFolder().copyFolder(src, des, filterFile);
// System.out.println("Continue ?y or n");
// answer = scanner.next();
// } while (answer.equalsIgnoreCase("Y"));
// scanner.close();
String srcStr = "F:/jpa";
String destStr = "D:/aa2";
File src = new File(srcStr);
File des = new File(destStr);
// System.out.println(src.getPath());
// System.out.println(src.getAbsolutePath());
// System.out.println(src.getCanonicalPath());
// if(src.isDirectory()){
// System.out.println(src.getName());
// }
new CopyFolder().copyFolder(src, des, filterFile);
}
/** * * @param folder * @param filterFile * @throws Exception */
public void copyFolder(File srcFolder, File destFolder, String[] filterFile)
throws Exception {
File[] files = srcFolder.listFiles();
if(null!=files)
for (File file : files) {
String filename = file.getName();
String pathname = destFolder + File.separator + filename;
File dest = new File(pathname);
if (file.isFile() && filename.lastIndexOf('.')!=-1) {
String sutff = filename.substring(filename.lastIndexOf('.'), filename.length()).toLowerCase();
for (String suff : filterFile) {
if (sutff.equals(suff)) {
File destPar = dest.getParentFile();
destPar.mkdirs();
if (!dest.exists()) {
dest.createNewFile();
}
copyFile(file, dest);
}
}
} else {
if(!dest.exists()){
dest.mkdirs();
}
copyFolder(file, dest, filterFile);
}
}
}
/***
* * copy file * * @param src * @param dest * @param status * @throws
* IOException
*/
private void copyFile(File src, File dest) throws Exception {
FileInputStream input = null;
FileOutputStream outstrem = null;
try {
input = new FileInputStream(src);
outstrem = new FileOutputStream(dest);
outstrem.getChannel().transferFrom(input.getChannel(), 0,input.available());
total++;
String temp =String.format("\ncopy:%s size:%s to: %s complate: %s", src,src.length(),dest,total);
System.out.print(temp);
} catch (Exception e) {
throw e;
} finally {
outstrem.flush();
outstrem.close();
input.close();
}
}
}
转载于:https://my.oschina.net/u/230843/blog/370895