首先自己动手使用递归实现文件夹的拷贝,接着使用Commons-IO实现同样的效果
//import org.apache.commons.io.FileUtils;
public class FileTest {
public static void main(String[] args) throws IOException {
//long start = System.currentTimeMillis();
//递归实现文件夹的拷贝
dirCopy("src", "src2");
//System.out.println(System.currentTimeMillis()-start);
//start = System.currentTimeMillis();
//Commons-IO实现文件夹拷贝
FileUtils.copyDirectory(new File("src"), new File("src2"));
//System.out.println(System.currentTimeMillis()-start);
}
public static void dirCopy(String srcPath, String destPath) {
File src = new File(srcPath);
if (!new File(destPath).exists()) {
new File(destPath).mkdirs();
}
for (File s : src.listFiles()) {
if (s.isFile()) {
fileCopy(s.getPath(), destPath + File.separator + s.getName());
} else {
dirCopy(s.getPath(), destPath + File.separator + s.getName());
}
}
}
public static void fileCopy(String srcPath, String destPath) {
File src = new File(srcPath);
File dest = new File(destPath);
//使用jdk1.7 try-with-resource 释放资源,并添加了缓存流
try(InputStream is = new BufferedInputStream(new FileInputStream(src));
OutputStream out =new BufferedOutputStream(new FileOutputStream(dest))) {
byte[] flush = new byte[1024];
int len = -1;
while ((len = is.read(flush)) != -1) {
out.write(flush, 0, len);
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
对于Commons-IO只需去官网下载Binaries版,并将commons-io-2.6.jar和commons-io-2.6-sources.jar(源代码)引入项目中即可
windows开发环境选择commons-io-2.6-bin.zip下载
http://commons.apache.org/proper/commons-io/download_io.cgi
//导入包
import org.apache.commons.io.FileUtils;
//Commons-IO复制文件
FileUtils.copyFile(new File("p.png"),new File("p-copy.png"));
//Commons-IO复制目录
FileUtils.copyDirectory(new File("lib"),new File("lib2"));