- 1 year ago
Java - Copy folder from windows network path
To copy a folder from a Windows network path using Java, you can utilize the Files
class from the java.nio.file
package. Here's an example:
javaimport java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class Main {
public static void main(String[] args) {
String sourceFolderPath = "\\\\network\\path\\to\\source\\folder";
String destinationFolderPath = "C:\\destination\\folder";
try {
Path sourcePath = Path.of(sourceFolderPath);
Path destinationPath = Path.of(destinationFolderPath);
// Copy the entire folder recursively
Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Folder copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, replace \\network\path\to\source\folder
with the actual network path of the source folder you want to copy, and replace C:\destination\folder
with the destination folder path where you want to copy the folder.
The code uses Path.of()
to create Path
objects for the source and destination folders. Then, it uses Files.copy()
to copy the entire folder from the source path to the destination path recursively. The StandardCopyOption.REPLACE_EXISTING
option ensures that if the destination folder already exists, it will be replaced.
Make sure that the user running the Java program has the necessary permissions to access the network path and write to the destination folder.
After running the code, the specified source folder will be copied to the destination folder on the local system.