FTPClient下載文件0kb問題


困擾了2天的問題終於解決

錯誤代碼

/**
    * @Description: 從ftp服務器下載文件到指定輸出流
    * @param remotePath,fileName,outputStream FTP服務器上的相對路徑,文件名,輸出流
    * @return 布爾值 成功返回true,異常返回false
    * @author Beyond
    * @date 2021/6/5 14:34
    */
    public static boolean downloadFile(String remotePath, String fileName, OutputStream outputStream) {
        boolean result = false;
        try {
            if (initFtpClient()){
                return false;
            }
            // 轉移到FTP服務器目錄
            ftp.changeWorkingDirectory(remotePath);
            // 通知服務器開通給一個端口,防止掛死
            ftp.enterLocalPassiveMode();
            // 取得指定文件夾下文件列表
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                // 取得指定文件並下載
                if (ff.getName().equals(fileName)) {
                    ftp.enterLocalPassiveMode();
                    ftp.retrieveFile(remotePath+"/"+fileName,outputStream);
                    result = true;
                }
            }
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

錯誤原因
image
修正后代碼

/**
    * @Description: 從ftp服務器下載文件到指定輸出流
    * @param remotePath,fileName,outputStream FTP服務器上的相對路徑,文件名,輸出流
    * @return 布爾值 成功返回true,異常返回false
    * @author Beyond
    * @date 2021/6/5 14:34
    */
    public static boolean downloadFile(String remotePath, String fileName, OutputStream outputStream) {
        boolean result = false;
        try {
            if (initFtpClient()){
                return false;
            }
            // 轉移到FTP服務器目錄
            ftp.changeWorkingDirectory(remotePath);
            // 通知服務器開通給一個端口,防止掛死
            ftp.enterLocalPassiveMode();
            // 取得指定文件夾下文件列表
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                // 取得指定文件並下載
                if (ff.getName().equals(fileName)) {
                    ftp.enterLocalPassiveMode();
                    ftp.retrieveFile(
                            new String(fileName.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1),
                            outputStream);
                    result = true;
                }
            }
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

附圖顯示成功后結果
image
image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM