基於 Apache Commons Net FTPClient 封裝的生產級工具類,支援編碼處理、被動模式、流式傳輸、目錄遞歸創建。
uploadFile():單文件上傳(緩衝流)sendFile():流式上傳(大文件、進度監控)downFile():單文件下載list():目錄列表(過濾 . .. Thumbs.db)deleteFile():遞歸刪除目錄及文件buildList():遞歸創建遠程目錄路徑hasSubFolder():判斷目錄是否有子目錄public static final String PLATFORM_CHARSET = "GB2312"; // 或 UTF-8 String remotePath = new String(localPath.getBytes(PLATFORM_CHARSET), "ISO-8859-1");
FTP 協議默認 ISO-8859-1,雙向轉換避免中文亂碼。
ftp.enterLocalPassiveMode(); // 防火牆友好 ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // 圖片/文檔不損壞
OutputStream os = ftp.storeFileStream(remoteName);
byte[] buffer = new byte[ftp.getBufferSize()];
int n; long transferred = 0;
while ((n = input.read(buffer)) != -1) {
os.write(buffer);
transferred += n;
// 可回調進度
}
os.close(); // 必須關閉流完成傳輸
public static void buildList(FTPClient ftp, String path) throws IOException {
StringTokenizer st = new StringTokenizer(path, "/");
StringBuilder dir = new StringBuilder();
while (st.hasMoreTokens()) {
dir.append("/").append(st.nextToken());
String d = dir.toString();
if (d.startsWith("/")) d = d.substring(1);
ftp.makeDirectory(d); // 已存在會拋異常,生產環境需捕獲忽略
}
}
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
import java.util.*;
public class FTPUtil {
public static final String PLATFORM_CHARSET = "GB2312";
// uploadFile, sendFile, downFile, list, deleteFile, buildList, hasSubFolder
// 見上方核心功能與關鍵實現細節
}
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
PoolingFTPClient)避免頻繁建連setConnectTimeout()/setDefaultTimeout()