java 实现FTP协议多个文件的上传
时间: 2023-10-27 20:04:52 浏览: 171
FTP 协议是文件传输协议,用于在网络上传输文件。Java 通过 FTPClient 类提供了 FTP 客户端的实现,可以使用该类实现 FTP 文件上传。
下面是一个实现 FTP 协议多个文件上传的示例代码:
```java
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FTPUploader {
private String server;
private int port;
private String user;
private String password;
private FTPClient ftpClient;
public FTPUploader(String server, int port, String user, String password) {
this.server = server;
this.port = port;
this.user = user;
this.password = password;
}
public void connect() throws IOException {
ftpClient = new FTPClient();
ftpClient.connect(server, port);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
throw new IOException("FTP server refused connection.");
}
boolean success = ftpClient.login(user, password);
if (!success) {
throw new IOException("Could not login to the FTP server.");
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
}
public void disconnect() throws IOException {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
public void uploadFiles(String directory, File[] files) throws IOException {
if (!ftpClient.changeWorkingDirectory(directory)) {
throw new IOException("Could not change working directory to " + directory);
}
for (File file : files) {
String filename = file.getName();
try (FileInputStream inputStream = new FileInputStream(file)) {
boolean success = ftpClient.storeFile(filename, inputStream);
if (!success) {
throw new IOException("Could not upload file " + filename);
}
}
}
}
}
```
使用该类的示例代码如下:
```java
public static void main(String[] args) throws IOException {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String password = "password";
String directory = "/upload";
File[] files = new File[] {new File("file1.txt"), new File("file2.txt"), new File("file3.txt")};
FTPUploader uploader = new FTPUploader(server, port, user, password);
uploader.connect();
uploader.uploadFiles(directory, files);
uploader.disconnect();
}
```
以上代码实现了连接到 FTP 服务器,切换到指定目录,然后上传多个文件的操作。其中,`FTPClient` 类提供了很多与 FTP 协议相关的方法,可以根据需要进行调用。
阅读全文