从ftp上读取文件,解决乱码问题,以byte[]返回文件数据


public byte[] readFileFromFtp(String url, String username, String password) throws Exception {
        byte[] fileByte = null;
        //从 URL 中获取对应的 IP、PORT 和下载文件名称
        url = url.replace("ftp://", "").replace("FTP://", "");
        String ip;
        String port;
        String fileName;
        if (url.contains(":")) {
            ip = url.split(":")[0];
            port = url.split(":")[1].split("/")[0];
            fileName = url.split(":")[1].split(port)[1];
        }
        //解决中文乱码问题
        fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
        //实例化 FTP 客户端
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            //连接 FTP 服务器
            ftpClient.connect(ip, Integer.parseInt(port));
            //获取 FTP 响应码
            int reply = ftpClient.getReplyCode();
            //如果 FTP 拒绝链接
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
            }
            //登录 FTP 服务器
            ftpClient.login(username, password);
            //设置被动模式,通知服务端开通端口传输数据
            ftpClient.enterLocalPassiveMode();
            ftpClient.setBufferSize(1024 * 1024);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.setControlEncoding(StandardCharsets.UTF_8.name());
            inputStream = ftpClient.retrieveFileStream(fileName);
            int readBytes;
            byte[] bytes = new byte[1024 * 1024];
       if (inputStream != null) { 
while ((readBytes = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, readBytes); }
          //若inputStream为null,调用此方法会产生卡死超时的现象 ftpClient.completePendingCommand(); ftpClient.changeToParentDirectory();
       } }
catch (Exception e) { throw new Exception(CommonResultTOConfig.ERROR_1801.getValue()); } finally { if (outputStream != null) { outputStream.flush(); fileByte = outputStream.toByteArray(); outputStream.close(); } if (inputStream != null) { inputStream.close(); } ftpClient.logout(); ftpClient.disconnect(); } return fileByte; }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM