Search code examples
javaftpfile-transferremote-serverwebdav

How to transfer files from one remote location to another using java?


I want to write java program to download files directly to remote server rather than downloading on local machine.

Remote server is FTP/WebDAV

So is there any library in java to download files directly to remote ftp/WebDAV server rather than saving it to local machine and uploading it.

Please lead in proper direction


Solution

  • Your question is too broad, but I would recommend you the following steps:

    1) Download the file into your system using the Java NIO

    2) Get the file you downloaded and send it to the web server you have access using the Ftp Client like following:

    FTPClient client = new FTPClient();
    try {
    client.connect("ftp.domain.com");
    client.login("username", "pass");
    FileInputStream fileInputStream = new FileInputStream("path_of_the_downloaded_file");
    client.storeFile(filename, fileInputStream );
    client.logout();
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
        if (fileInputStream != null) {
            fileInputStream .close();
        }
        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
    

    ============================= EDIT =================================

    Reply to comment: "but I don't want to store file locally, not even temporarily"

    Then you just need to store it in a byte array, and convert the byte array to an InputStream and send store the file to your server

        FTPClient client = new FTPClient();
        BufferedInputStream in = new BufferedInputStream(new URL("www.example.com/file.pdf").openStream());
        byte[] bytes = IOUtils.toByteArray(in);
        InputStream stream = new ByteArrayInputStream(bytes);
        client.connect("ftp.domain.com");
        client.login("username", "pass");
        client.storeFile("fileName", stream);
        stream.close();