我需要每天从远程FTP服务器下载一个文件,并将其内容作为InputStream(或至少作为byte[])提供给类以供进一步处理。理想情况下,我还应该避免任何磁盘写入。
有人能就如何使用XML或基于注释的配置来配置它提供一些建议吗?
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()
中的处理程序中。
在Spring Integration 3.0中添加了FtpRemoteFileTemplate
(但在4.0中添加了采用String而非Message<?>
的get()
变体)
SftpRemoteFileTemplate
也可用。