2 回答
TA贡献1943条经验 获得超7个赞
这是一个老问题,但我遇到了同样的问题,并且我能够在不假设本地文件的情况下解决它,例如使用 ByteArrayInputStream,所以这对于与 pise 遇到相同问题的人可能很有用。基本上,我们可以将输入流直接复制到远程文件的输出流中。
代码是这样的:
InputStream is = ... // you only need an input stream, no local file, e.g. ByteArrayInputStream
DefaultFileSystemManager fsmanager = (DefaultFileSystemManager) VFS.getManager();
FileSystemOptions opts = new FileSystemOptions();
FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
StaticUserAuthenticator auth = new StaticUserAuthenticator(host, username, password);
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
String ftpurl = "ftp://" + host + ":" + port + "/" + folder + "/" + filename;
FileObject remoteFile = fsmanager.resolveFile(ftpurl, opts);
try (OutputStream ostream = remoteFile.getContent().getOutputStream()) {
// either copy input stream manually or with IOUtils.copy()
IOUtils.copy(is, ostream);
}
boolean success = remoteFile.exists();
long size = remoteFile.getContent().getSize();
System.out.println(success ? "Successful, copied " + size + " bytes" : "Failed");
TA贡献1890条经验 获得超9个赞
/**
* Write the byte array to the given file.
*
* @param file The file to write to
* @param data The data array
* @throws IOException
*/
public static void writeData(FileObject file, byte[] data)
throws IOException {
OutputStream out = null;
try {
FileContent content = file.getContent();
out = content.getOutputStream();
out.write(data);
} finally {
close(out);
}
}
添加回答
举报