下面提供 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) {}
}
}
FTP 協議早期僅支持 ISO-8859-1,需雙向轉碼:new String(utf8Bytes, "ISO-8859-1") 發送,接收端再 `new String(isoBytes, "UTF-8")` 還原。