java 如何拷贝整个目录,类似xcopy

如题所述

字数有限制,只给你一个方法吧,大体思路就是递归调用的方式来实现
/**
* 拷贝整个文件目录
* @param source 源目录、文件
* @param destination 目的目录、文件
*/
public static void copyFiles(File source, File destination) {
 if (!source.exists()) {
//Log.warn(source.getAbsolutePath() + " 源文件或源路径不存在");
return;
}
if (destination.isFile()) {
//Log.warn(destination.getAbsolutePath() + " 目标不应该是文件, 应该是路径");
return;
}
else
destination.mkdirs();
//如果是文件
if (source.isFile()) {
try {
String filename = destination.getAbsolutePath() + File.separator + source.getName();
FileInputStream fis = new FileInputStream(source);
File file = new File(filename);
if (file.exists()) {
file.delete();
}
FileOutputStream fos = new FileOutputStream(file);
if(!StreamHelper.toOutputStream(fis, fos)) {
return;
}
fos.close();
fis.close();
Log.debug("复制 " + source.getAbsolutePath() + " 到 " + filename);
return;
}catch (IOException ex) {
Log.error(ex);
return;
}
}
//如果是目录
else {
File[] files = source.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
String path = destination.getAbsolutePath() + File.separator + files[i].getName();
File folder = new File(path);
copyFiles(files[i], folder);
}else {
copyFiles(files[i], destination);
}
}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-03-21
有两种方法可以使用:

1、我们可以使用java的File类,使用递归算法遍历文件夹及其所有层的子文件夹,这种写法非常繁琐且效率不高,不推荐使用。

2、直接使用Windows的xcopy命令
示例代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main( String[] args ) throws IOException
{
/*在dos窗口:xcopy C:\源文件 D:\源文件\/S/E*/
/*字符所需的格式:xcopy C:\\源文件 D:\\源文件\\/S/E*/
System.out.println( "请输入源文件的地址栏路径:" );
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
String input = br.readLine();
/*将地址中的单斜杠变为双斜杠*/
String from = input.replaceAll( "\\\\", "\\\\\\\\" );
/*获取文件名*/
String name_file = from.substring( from.lastIndexOf( "\\" ) + 1, from.length() );
/*把目标拷贝到D盘根目录*/
String to = "D:\\" + name_file + "\\/S/E";
/*拼装命令*/
String cmd = "cmd.exe /C xcopy " + from + " " + to;
/*执行命令*/
java.lang.Runtime.getRuntime().exec( cmd );
System.out.println( "文件拷贝完毕。" );
System.out.println( "文件已经拷贝到:D:\\" + name_file );
}
}本回答被网友采纳
第2个回答  2013-06-19
需要下载导入 commons-io-1.3.jar
/**
* 文件复制
* @param resFilePath 文件路径
* @param distFolder 复制保存路径
* */
public static boolean copyFile(String resFilePath, String distFolder) {
File resFile = new File(resFilePath);
File distFile = new File(distFolder);
try {
if (resFile.isDirectory()) {
FileUtils.copyDirectoryToDirectory(resFile, distFile);
} else if (resFile.isFile()) {
FileUtils.copyFileToDirectory(resFile, distFile, true);
}
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("file Backup error!");
return false;
}
}
第3个回答  2013-06-19
支持一楼.通过递归.遍历获得的每个File
判断再copy..
第4个回答  2013-06-19
支持1楼,用递归算法来实现。
相似回答