I provided an alternate solution without the need to use a third party, such as apache FileUtils. This can be done through the command line.
I tested this out on Windows and it works for me. A Linux solution follows.
Here I am utilizing Windows xcopy command to copy all files including subdirectories.
The parameters that I pass are defined as per below.
- /e - Copies all subdirectories, even if they are empty.
- /i - If Source is a directory or contains wildcards and Destination
does not exist, xcopy assumes Destination specifies a directory name
and creates a new directory. Then, xcopy copies all specified files
into the new directory.
- /h - Copies files with hidden and system file attributes. By default,
xcopy does not copy hidden or system files
My example(s) utilizes the ProcessBuilder class to construct a process to execute the copy(xcopy & cp) commands.
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();
}
Or a combo that can work on both Windows or Linux environments.
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")) { // setup WINDOWS environment
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")){ // setup LINUX environment
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();
}
}