4

I'd like to copy all contents of a local directory, including subdirectories, to a samba share.

Is there an easy way to do this? Something like the SmbFile.copyTo() when source AND target are on SMB.

user2586521
  • 41
  • 1
  • 2

2 Answers2

1

If you define both the source and destination as SmbFiles you can just use SmbFile.copyTo(). For example

  String userName = "USERNAME";
  String password = "PASSWORD";
  String user = userName + ":" + password;  

  String destinationPath = "smb://destinationlocation.net";
  String sourcePath = "smb://sourcelocation.net";

  NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);               

  SmbFile dFile = new SmbFile(destinationPath, auth);
  SmbFile sFile = new SmbFile(sourcePath, auth);

  sFile.copyTo(dFile);

The directory and its contents should all be copied from the source location to the destination location.

0

I've done something similar just now and found this nearly 10 years old question. The below code copies a local folder with all subfolders and files to an SMB share.

It uses Files.walk from java.nio to "walk" through all local files and folders. If it is a folder, it calls mkdirs(), which creates all required folders on the share, in case they are not already there. Files are created if necessary and file content is copied with Files.copy. If a file already exists on the share, its content will be overwritten.

The code uses try-with-resource blocks in order to make sure opened resources are closed.

String srcUrl = "path/to/local/folder";
String destUrl = "smb://user:password@host/share";

try(Stream<Path> pathStream = Files.walk(Paths.get(srcUrl))) {
    pathStream.forEach(sourcePath -> {
        try {
            SmbFile destinationFile =
                new SmbFile(destUrl + sourcePath.toString().substring(srcUrl.length()));

            if(Files.isDirectory(sourcePath)) {
                if(!destinationFile.exists()) {
                    // create any missing directories
                    destinationFile.mkdirs();
                }
            }
            else {
                // it's a file -> create file (if it's not already there) and copy content
                if(!destinationFile.exists()) {
                    destinationFile.createNewFile();
                }

                try(SmbFileOutputStream out = new SmbFileOutputStream(destinationFile)) {
                    Files.copy(sourcePath, out);
                }
            }
        }
        catch(IOException e) {
            throw new RuntimeException(e);
        }
    });
}
catch(Exception e) {
    logger.error("failed to copy from {} to {}", srcUrl, destUrl, e);
}
Sky
  • 674
  • 8
  • 22