在上载和下载文件时使用的内存泄漏(可能是由于使用ChannelSftp.get("file_name"))? [英] Memory leak using while uploading and downloading a file (may be because of using ChannelSftp.get( "file_name") )?

查看:568
本文介绍了在上载和下载文件时使用的内存泄漏(可能是由于使用ChannelSftp.get("file_name"))?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请您介绍ChannelSftp.get( "file_name")的内部工作方式?如果此功能经常使用,使用此功能从文件列表(600个10 kb的文件)中获取单个文件是否会在Tomcat8中引起内存泄漏问题?

Can you please tell the internal working of ChannelSftp.get( "file_name")? Will the use of this function to get a single file from a list of files (600 files of 10 kb) can cause memory leakage issues in Tomcat8, if this function is used frequently?

这是用于从远程服务器上载和提取文件的代码.

This is the code which is used for uploading and fetching files from remote server.

public String connectRemote(String host, String user, String password, String 
    remotePath, String sFileName) throws IOException, JSchException, SftpException 
{
    try {
        String sFileNames ="";
        Session session = connectSFTP(host, user, password);

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp chan = (ChannelSftp) channel;

        try {

            String ftpRemoteDirectory = "/Irismedical/Outbox_Eligibility";

            chan.cd(ftpRemoteDirectory);

            File ftest = new File(sFileName);

            chan.put(new FileInputStream(ftest), ftest.getName());

            sFileNames =  ftest.getName();

        }
        catch (Exception e) {
            chan.disconnect();
            session.disconnect();
            return null;
        }

        chan.cd("/Irismedical/Inbox/Eligibility");

        String sRes = null;
        for (int i = 0;i<6 ; i++) {

            try {
                  sRes = convertInputStreamToString(
                             chan.get(sFileNames+"_Response_271_1.edi"));

                 if (sRes  != null ) {

                     break;

            } catch (Exception e ) {
                if (i<3) {
                    Thread.sleep(3000);
                } else {
                    Thread.sleep(5000);
                }
            }
        }
                    session.disconnect();

        return sRes;
    }
    catch (Exception e) {
        }
        return null;
    }
}

private static String convertInputStreamToString(InputStream inputStream) 
    throws IOException {

    ByteArrayOutputStream result = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) != -1) {
        result.write(buffer, 0, length);
    }

    return result.toString(StandardCharsets.UTF_8.name());
}

推荐答案

您必须处理流.

上传代码中的FileInputStream和下载代码中ChannelSftp.get返回的InputStream.

Both the FileInputStream in your upload code and the InputStream returned by ChannelSftp.get in your download code.

请参见以Java语言处理流.

这篇关于在上载和下载文件时使用的内存泄漏(可能是由于使用ChannelSftp.get("file_name"))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆