java如何访问ftp
访问FTP的方法
在Java中访问FTP服务器可以通过多种方式实现,常用的方法包括使用Apache Commons Net库和Java原生API。以下是两种方法的详细说明。
使用Apache Commons Net库
Apache Commons Net是一个广泛使用的库,提供了FTP客户端的功能。需要先下载并添加该库到项目中。
添加依赖(Maven):

<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version>
</dependency>
连接FTP服务器并上传文件:
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FTPExample {
public static void main(String[] args) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("ftp.example.com", 21);
ftpClient.login("username", "password");
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
File localFile = new File("local.txt");
FileInputStream inputStream = new FileInputStream(localFile);
boolean success = ftpClient.storeFile("remote.txt", inputStream);
inputStream.close();
if (success) {
System.out.println("File uploaded successfully.");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用Java原生API
Java原生API通过java.net.URL和java.net.URLConnection类支持FTP协议,但功能较为有限。

下载文件示例:
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class NativeFTPExample {
public static void main(String[] args) {
String ftpUrl = "ftp://username:password@ftp.example.com/remote.txt";
String savePath = "local.txt";
try {
URL url = new URL(ftpUrl);
URLConnection conn = url.openConnection();
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
FileOutputStream out = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.close();
in.close();
System.out.println("File downloaded successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
确保FTP服务器支持被动模式(PASV)或主动模式(PORT),根据网络环境选择合适的模式。
处理文件传输时,明确文件类型(ASCII或二进制),避免文件损坏。
在生产环境中,使用SSL/TLS加密的FTPS或SFTP协议更安全。






