最近的一個(gè)需求為掃描FTP文件夾下的所有文件用于前端下載, 要求多層文件夾內(nèi)的文件也能被掃到.
多層文件夾一般就要用到遞歸了, 上代碼:
/**
* 遞歸獲取所有FTP文件
*
* @param ftp ftp客戶端
* @param path 路徑
* @param fileList 文件列表
* @throws IOException 異常
*/
private void getAllFiles(FTPClient ftp, String path, List<String> fileList) throws IOException {
// 切換路徑
ftp.changeWorkingDirectory(path);
FTPFile[] ftpFiles = ftp.listFiles();
for (FTPFile ftpFile : ftpFiles) {
if (ftpFile.getType() == 0) {
// 文件直接添加
fileList.add(ftpFile.getName());
continue;
}
if (ftpFile.getType() == 1) {
// 文件夾修改路徑進(jìn)行遞歸
String sb = path +
"/" +
ftpFile.getName();
getAllFiles(ftp, sb, fileList);
}
}
}
?調(diào)用該方法:
// 從ftp服務(wù)器獲取文件列表
// 創(chuàng)建FTPClient對(duì)象
FTPClient ftp = new FTPClient();
try {
int reply;
// 連接前設(shè)置字符編碼
ftp.setCharset(StandardCharsets.UTF_8);
ftp.setControlEncoding("UTF-8");
// 連接FTP服務(wù)器
// 如果采用默認(rèn)端口,可以使用ftp.connect(url)的方式直接連接FTP服務(wù)器
ftp.connect(serverIP);
// 不需要賬號(hào)密碼時(shí)匿名登錄
ftp.login("anonymous", null);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new ApplicationException("connecting to ftp error.");
}
// 設(shè)置文件類型為二進(jìn)制 (必須, 否則文件無法打開, 血的教訓(xùn))
ftp.setFileType(FTP.BINARY_FILE_TYPE);
// 獲取文件
// String path = "/temp/test";
String path = remotePath;
List<String> fileList = new ArrayList<>();
getAllFiles(ftp, path, fileList);
調(diào)用完后, fileList中就有指定目錄下的所有文件名
?依賴:文章來源:http://www.zghlxwxcb.cn/news/detail-639049.html
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.7</version>
</dependency>
定時(shí)調(diào)用邏輯使用的是PowerJob, 嫌麻煩可以直接使用spring自帶的@Scheduled注解.文章來源地址http://www.zghlxwxcb.cn/news/detail-639049.html
到了這里,關(guān)于獲取FTP服務(wù)器某個(gè)目錄下的所有文件列表的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!