从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];
            while ((readBytes = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, readBytes);
            }
            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;
    }

相关