【发布时间】:2014-11-10 15:26:58
【问题描述】:
我需要每天从远程 FTP 服务器下载一个文件,并将其内容作为 InputStream(或至少作为 byte[])提供给一个类以供进一步处理。理想情况下,我还应该避免任何磁盘写入。
谁能提供一些关于如何使用 XML 或基于注释的配置来配置它的建议?
【问题讨论】:
标签: java spring ftp spring-integration
我需要每天从远程 FTP 服务器下载一个文件,并将其内容作为 InputStream(或至少作为 byte[])提供给一个类以供进一步处理。理想情况下,我还应该避免任何磁盘写入。
谁能提供一些关于如何使用 XML 或基于注释的配置来配置它的建议?
【问题讨论】:
标签: java spring ftp spring-integration
Spring Integration 目前没有预配置的适配器来“流式传输”文件;但是,它确实有一个底层组件 (FtpRemoteFileTemplate) 支持这种访问。
您可以将远程文件模板配置为 bean(使用 XML 或 Java Config) - 为其提供会话工厂等,并调用 get() 方法之一:
/**
* Retrieve a remote file as an InputStream.
*
* @param remotePath The remote path to the file.
* @param callback the callback.
* @return true if the operation was successful.
*/
boolean get(String remotePath, InputStreamCallback callback);
/**
* Retrieve a remote file as an InputStream, based on information in a message.
*
* @param message The message which will be evaluated to generate the remote path.
* @param callback the callback.
* @return true if the operation was successful.
*/
boolean get(Message<?> message, InputStreamCallback callback);
这样的……
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
boolean success = template.get("foo.txt", new InputStreamCallback() {
@Override
public void doWithInputStream(InputStream stream) throws IOException {
FileCopyUtils.copy(stream, baos);
}
});
if (success) {
byte[] bytes = baos.toByteArray());
...
}
或者您可以将输入流直接传递到doWithInputStream() 中的处理程序。
FtpRemoteFileTemplate 是在 Spring Integration 3.0 中添加的(但在 4.0 中添加了采用字符串而不是 Message<?> 的 get() 变体。
SftpRemoteFileTemplate 也可用。
【讨论】: