首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java FTP 文件上傳下載:中文亂碼、多文件、慢速度解決方案

     編輯:Java 相關知識

注意:原文內容與標題不符,實為桶排序算法重複

下面提供 FTP 實戰核心代碼模板:

Apache Commons Net FTP 工具類

public class FtpUtils {
    private FTPClient ftp = new FTPClient();

    public void connect(String host, int port, String user, String pass) throws IOException {
        ftp.connect(host, port);
        ftp.login(user, pass);
        ftp.setControlEncoding("UTF-8");        // 解決中文目錄亂碼
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();            // 被動模式穿透防火牆
        ftp.setBufferSize(1024 * 1024);         // 1MB 緩衝提速
    }

    public boolean upload(String localPath, String remoteDir, String fileName) {
        try (FileInputStream in = new FileInputStream(localPath)) {
            ftp.changeWorkingDirectory(remoteDir);
            return ftp.storeFile(new String(fileName.getBytes("UTF-8"), "ISO-8859-1"), in);
        } catch (IOException e) { return false; }
    }

    public boolean download(String remotePath, String localDir, String fileName) {
        try (FileOutputStream out = new FileOutputStream(localDir + File.separator + fileName)) {
            return ftp.retrieveFile(new String(remotePath.getBytes("UTF-8"), "ISO-8859-1"), out);
        } catch (IOException e) { return false; }
    }

    public void disconnect() {
        try { if (ftp.isConnected()) ftp.logout(); } catch (IOException ignored) {}
    }
}

關鍵優化點

  • 編碼:控制連接 UTF-8,文件名轉 ISO-8859-1(FTP 協議要求)
  • 被動模式:`enterLocalPassiveMode()` 解決防火牆/NAT 導致連接超時
  • 大緩衝:`setBufferSize(1MB)` 明顯提升大文件傳輸速度
  • 批量操作:`ftp.listFiles()` 獲取列表後循環下載,避免重複連接

中文亂碼根因

FTP 協議早期僅支持 ISO-8859-1,需雙向轉碼:new String(utf8Bytes, "ISO-8859-1") 發送,接收端再 `new String(isoBytes, "UTF-8")` 還原。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved