JAVA 中不错的开源FTP组件:commons-net

时间:2022-05-29 15:19:41

第一步:引入jar到pom.xml、

        <!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>

第二步:demo代码示例

以下代码实现了,连接ftp,遍历ftp服务器上的目录结构

package com.dx.ftp;

import java.io.IOException;
import java.net.MalformedURLException; import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply; /**
* Hello world!
*/
public class App {
public static void main(String[] args) throws IOException {
String hostname = "ftp1.linuxidc.com";
Integer port = 21;
String username = "ftp1.linuxidc.com";
String password = "www.linuxidc.com";
FTPClient ftpClient = new FTPClient(); // ftpClient.setControlEncoding("utf-8");
ftpClient.setControlEncoding("GB2312"); try {
System.out.println("connecting...ftp服务器:" + hostname + ":" + port);
ftpClient.connect(hostname, port); // 连接ftp服务器
ftpClient.login(username, password); // 登录ftp服务器
int replyCode = ftpClient.getReplyCode(); // 是否成功登录服务器
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("connect failed...ftp服务器:" + hostname + ":" + port);
}
System.out.println("connect successfu...ftp服务器:" + hostname + ":" + port);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory("/"); deepLoop(ftpClient, "/"); System.out.println("Hello World!");
} private static void deepLoop(FTPClient ftpClient, String dir) throws IOException {
FTPFile[] files = ftpClient.listFiles(dir);
for (FTPFile file : files) {
if (file.isDirectory()) {
if (!file.getName().startsWith(".")) {
System.out.println("directory ---------> " + dir + "/" + file.getName());
deepLoop(ftpClient, dir + "/" + file.getName());
}
} else if (file.isFile()) {
System.out.println("file ---------> " + dir + "/" + file.getName());
} else if (file.isSymbolicLink()) {
System.out.println("symboliclink---------> " + file.getName());
} else if (file.isUnknown()) {
System.out.println("unknown ---------> " + file.getName());
}
}
}
}