java ftp工具类
时间: 2023-10-16 09:11:07 浏览: 42
以下是一个简单的 Java FTP 工具类示例,可以用来上传和下载文件:
```java
import java.io.*;
import org.apache.commons.net.ftp.*;
public class FTPUtils {
private static FTPClient ftpClient = new FTPClient();
public static void uploadFile(String server, int port, String user, String password, String filePath, String remoteDir)
throws IOException {
ftpClient.connect(server, port);
ftpClient.login(user, password);
File file = new File(filePath);
FileInputStream input = new FileInputStream(file);
ftpClient.changeWorkingDirectory(remoteDir);
ftpClient.storeFile(file.getName(), input);
input.close();
ftpClient.logout();
ftpClient.disconnect();
}
public static void downloadFile(String server, int port, String user, String password, String remoteFilePath, String localDir)
throws IOException {
ftpClient.connect(server, port);
ftpClient.login(user, password);
File localFile = new File(localDir + "/" + remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1));
OutputStream output = new FileOutputStream(localFile);
ftpClient.retrieveFile(remoteFilePath, output);
output.close();
ftpClient.logout();
ftpClient.disconnect();
}
}
```
这个工具类使用了 Apache Commons Net 库来实现 FTP 操作。它包含了两个方法:
- `uploadFile()`:用于将本地文件上传到远程 FTP 服务器。
- `downloadFile()`:用于从远程 FTP 服务器下载文件到本地。
在使用这个工具类时,需要提供 FTP 服务器的地址、端口、用户名、密码、本地文件路径、远程目录等参数。