Schedule remote file download over FTP and process file in memory with Spring Integration

依然范特西╮ 提交于 2021-01-28 17:57:04

问题


I need to download a file from a remote FTP server every day and provide its contents to a class as an InputStream (or at least as byte[]) for further processing. Ideally I should also avoid any disk write.

Can anyone give some advice on how to configure it with an XML or an annotation based configuration?


回答1:


Spring Integration currently doesn't have a pre-configured adapter to 'stream' a file; it does, however, have an underlying component (FtpRemoteFileTemplate) that enables such access.

You can configure the remote file template as a bean (using XML or Java Config) - giving it a session factory etc, and invoke one of the get() methods:

/**
 * 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);

Something like this...

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

Or you can pass the input stream directly into your handler in doWithInputStream().

The FtpRemoteFileTemplate was added in Spring Integration 3.0 (but the get() variant that takes a String rather than a Message<?> was added in 4.0).

SftpRemoteFileTemplate is also available.



来源:https://stackoverflow.com/questions/26847113/schedule-remote-file-download-over-ftp-and-process-file-in-memory-with-spring-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!