在Java中连接FTP服务器可以使用Apache Commons Net库提供的FTPClient类。以下是一个简单的示例代码,演示如何连接到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.FileOutputStream;
import java.io.IOException;
public class FTPExample {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String username = "your-username";
String password = "your-password";
FTPClient ftpClient = new FTPClient();
try {
// 连接到FTP服务器
ftpClient.connect(server, port);
ftpClient.login(username, password);
// 设置文件传输模式为二进制
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 上传文件到FTP服务器
File fileToUpload = new File("path/to/local/file.txt");
FileInputStream inputStream = new FileInputStream(fileToUpload);
ftpClient.storeFile("remote/file.txt", inputStream);
inputStream.close();
// 下载文件从FTP服务器
File fileToDownload = new File("path/to/local/downloaded-file.txt");
FileOutputStream outputStream = new FileOutputStream(fileToDownload);
ftpClient.retrieveFile("remote/file.txt", outputStream);
outputStream.close();
// 断开连接
ftpClient.logout();
ftpClient.disconnect();
System.out.println("文件上传和下载成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的示例代码中,你需要替换以下信息:
-
server
:FTP服务器的主机名或IP地址。
-
port
:FTP服务器的端口,默认为21。
-
username
:登录FTP服务器的用户名。
-
password
:登录FTP服务器的密码。
-
fileToUpload
:要上传到FTP服务器的本地文件路径。
-
fileToDownload
:要从FTP服务器下载的文件保存的本地路径。
该示例使用FTPClient
类连接到FTP服务器,并通过login
方法进行身份验证。然后,设置文件传输模式为二进制(FTP.BINARY_FILE_TYPE
),以确保正确传输文件的内容。之后,使用storeFile
方法上传文件到FTP服务器,使用retrieveFile
方法从FTP服务器下载文件。
请确保在使用Apache Commons Net库之前,已将其添加为项目的依赖项。你可以在Maven中添加以下依赖:
Maven:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>