從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