public static List<String> listAllFiles(String hostname, int port, String username, String password, String remotePath) {
FTPClient ftpClient = new FTPClient();
List<String> result = new ArrayList<>();
try {
//连接FTP服务器
ftpClient.connect(hostname, port);
//登录FTP服务器
ftpClient.login(username, password);
//验证FTP服务器是否登录成功
int replyCode = ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(replyCode)){
return null;
}
if (remotePath.startsWith("/") && remotePath.endsWith("/")) {
FTPFile[] files = ftpClient.listFiles(remotePath);
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
//print(files[i].getName());
result.add( remotePath + files[i].getName() );
} else if (files[i].isDirectory()) {
result.addAll( listAllFiles( hostname, port, username, password, remotePath + files[i].getName() + "/" ) );
}
}
}
return result;
} catch (IOException e) {
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try {
ftpClient.logout();
} catch (IOException e) {}
}
}
return null;
}
调用
println( listAllFiles( hostname, port, username, password, "/" ) );