Search code examples
javanionetwork-share

Copy a file to a Windows remote machine from Linux using java.nio.file.Files.copy()


I am working on a Spring Boot application and I need to copy a file to a remote machine.

When I run the program on a Windows machine, it works fine. Here is the code:

void copyImage(MultipartFile image, String name) {

    name = name + "." + FileUtils.getExtension(image);

    Path path = Paths.get("\\<remote-machine>\path\to\repository\" + name);

    try {
        Files.copy(image.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        // Handle exception here
    }
}

As expected, this program doesn't work when I run it on Linux (Pop!_OS). I believe the argument passed to Paths.get() is not properly formatted, since Windows and Linux treat paths differently. Any idea how to make this method work on Linux?


Solution

  • Linux does not support UNC paths natively - it does not understand that such a path is meant to refer to a network share. You have several options:

    • use a Java library that implements network share access using the SMB protocol. Some of the actively supported libraries are JCIFS and SMBJ. This should make your application portable (you can run it both on Linux and Windows), but you depend on an additional library and must use its custom API to access remote files
    • mount the remote share on Linux as a CIFS volume (official Ubuntu guide). Then the remote share becomes accessible as if it was a local directory on Linux. In this case you can keep using java.nio to access/copy files, but need to make sure to make the root path to your share configurable (eg. \\host\share on Windows and /mnt/share on Linux).