我提供了一种替代方案,无需使用第三方工具,如apache FileUtils。这可以通过命令行完成。
我在Windows上测试过,对我有效。下面是Linux的解决方案。
在这里,我利用Windows xcopy 命令来复制包括子目录在内的所有文件。我传递的参数如下所定义。
- /e - 复制所有子目录,即使它们为空。
- /i - 如果源是目录或包含通配符,并且目标不存在,则 xcopy 假定目标指定一个目录名称并创建一个新目录。然后,xcopy 将所有指定的文件复制到新目录中。
- /h - 复制带有隐藏和系统文件属性的文件。默认情况下,xcopy 不会复制隐藏或系统文件
我的示例利用 ProcessBuilder 类构建进程来执行复制(xcopy & cp)命令。
Windows:
String src = "C:\\srcDir";
String dest = "C:\\destDir";
List<String> cmd = Arrays.asList("xcopy", src, dest, "/e", "/i", "/h");
try {
Process proc = new ProcessBuilder(cmd).start();
BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = inp.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Linux:
String src = "srcDir/";
String dest = "~/destDir/";
List<String> cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);
try {
Process proc = new ProcessBuilder(cmd).start();
BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = inp.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
或者是一个可以在Windows或Linux环境下工作的组合。
private static final String OS = System.getProperty("os.name");
private static String src = null;
private static String dest = null;
private static List<String> cmd = null;
public static void main(String[] args) {
if (OS.toLowerCase().contains("windows")) {
src = "C:\\srcDir";
dest = "C:\\destDir";
cmd = Arrays.asList("xcopy", src, dest, "/e", "/i", "/h");
System.out.println("on: " + OS);
} else if (OS.toLowerCase().contains("linux")){
src = "srcDir/";
dest = "~/destDir/";
cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);
System.out.println("on: " + OS);
}
try {
Process proc = new ProcessBuilder(cmd).start();
BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = inp.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}