Spring-Integration,将文件上传到SFTP远程服务器-java.lang.OutOfMemoryError:直接缓冲内存

时间:2018-11-21 13:04:21

标签: java file spring-boot upload sftp

在SpringBoot应用程序中,我已使用Spring Integration将文件上传到远程SFTP服务器。
下面是我用来将文件传输到SFTP服务器的代码片段。

protected String transfer(String downloadDirectory) {
        File[] files = new File(downloadDirectory).listFiles();
        byte[] payload = null;
        String path = null;
        try {

            path = getSftpPath(downloadDirectory);
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    payload = Files.readAllBytes(Paths.get(files[i].toURI()));
                    gateway.upload(payload, files[i].getName(), path);
                }
            }
        } catch (Exception e) {

            throw new Exception(e);
        }
        return path;
    }

上传方法声明和MessageHandler如下

@MessagingGateway(asyncExecutor = "sftpAsync")
    public interface UploadGateway {
        @Gateway(requestChannel = "toSftpChannel")
        void upload(@Payload byte[] file, @Header("filename") String filename, @Header("path") String path);
    }

 @Bean
    @ServiceActivator(inputChannel = "toSftpChannel")
    public MessageHandler handler() {
        SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());
        ExpressionParser expressionParser = new SpelExpressionParser();
        handler.setRemoteDirectoryExpression(expressionParser.parseExpression("headers['path']"));
        handler.setFileNameGenerator(msg -> (String) msg.getHeaders().get("filename"));
        handler.setAutoCreateDirectory(true);
        return handler;
    }

它可以很好地将文件上传到远程SFTP服务器。但是执行几次后,它开始显示

java.lang.OutOfMemoryError: Direct buffer memory
    at java.nio.Bits.reserveMemory(Unknown Source)
    at java.nio.DirectByteBuffer.<init>(Unknown Source)
    at java.nio.ByteBuffer.allocateDirect(Unknown Source)
    at sun.nio.ch.Util.getTemporaryDirectBuffer(Unknown Source)
    at sun.nio.ch.IOUtil.read(Unknown Source)
    at sun.nio.ch.FileChannelImpl.read(Unknown Source)
    at sun.nio.ch.ChannelInputStream.read(Unknown Source)
    at sun.nio.ch.ChannelInputStream.read(Unknown Source)
    at sun.nio.ch.ChannelInputStream.read(Unknown Source)
    at java.nio.file.Files.read(Unknown Source)
    at java.nio.file.Files.readAllBytes(Unknown Source)

payload = Files.readAllBytes(Paths.get(files[i].toURI()));是抛出上述错误消息的行。

据我了解,我正在将整个文件读入字节数组,因此出现此错误。由于我需要整个文件发送到上载方法,因此我采用了byte []方法。

我已经检查了以下提到的线程。

Byte[] and java.lang.OutOfMemoryError reading file by bits

java.lang.OutOfMemoryError: Direct buffer memory when invoking Files.readAllBytes

但是上载方法需要整个文件,而不是字节流或数据块(如果我错了,请纠正我)。

因此,避免上述问题的任何建议都是有帮助的。

谢谢。

0 个答案:

没有答案