如何使用 java 将文件从一个远程位置传输到另一个位置?

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

我想编写 java 程序直接将文件下载到远程服务器,而不是在本地机器上下载。

远程服务器是 FTP/WebDAV

所以 java 中是否有任何库可以直接将文件下载到远程 ftp/WebDAV 服务器,而不是将其保存到本地计算机并上传。

请引导正确的方向

你的问题太笼统了,但我建议你按照以下步骤操作:

1) 使用 Java NIO

下载文件到您的系统

2) 获取您下载的文件并将其发送到您可以使用 Ftp Client 访问的 Web 服务器,如下所示:

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();
}
}

=============================编辑=============== ==================

回复评论:"but I don't want to store file locally, not even temporarily"

然后你只需要将它存储在一个字节数组中,并将字节数组转换为一个 InputStream 并将文件存储到你的服务器

    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();