java ftp详解_Java操作FTP工具类(实例详解)
时间: 2023-12-02 07:02:28 浏览: 136
java操作FTP工具类
Java可以通过FTP工具类来操作FTP,以下是一个示例:
```
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPUtil {
private static final String FTP_ADDRESS = "ftp服务器地址";
private static final int FTP_PORT = 21;
private static final String FTP_USERNAME = "ftp用户名";
private static final String FTP_PASSWORD = "ftp密码";
// 连接到FTP服务器
public static FTPClient connectFTP() throws SocketException, IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(FTP_ADDRESS, FTP_PORT);
ftpClient.login(FTP_USERNAME, FTP_PASSWORD);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
ftpClient.disconnect();
throw new IOException("连接FTP服务器失败");
}
return ftpClient;
}
// 上传文件到FTP服务器
public static void uploadFile(String remotePath, String fileName, InputStream input) throws IOException {
FTPClient ftpClient = null;
try {
ftpClient = connectFTP();
ftpClient.changeWorkingDirectory(remotePath); // 切换到上传目录
ftpClient.storeFile(fileName, input);
} finally {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
}
}
}
// 从FTP服务器下载文件
public static void downloadFile(String remotePath, String fileName, OutputStream output) throws IOException {
FTPClient ftpClient = null;
try {
ftpClient = connectFTP();
ftpClient.changeWorkingDirectory(remotePath); // 切换到下载目录
ftpClient.retrieveFile(fileName, output);
} finally {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
}
}
}
// 删除FTP服务器上的文件
public static boolean deleteFile(String remotePath, String fileName) throws IOException {
FTPClient ftpClient = null;
try {
ftpClient = connectFTP();
ftpClient.changeWorkingDirectory(remotePath); // 切换到删除目录
return ftpClient.deleteFile(fileName);
} finally {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
}
}
}
}
```
使用方式:
上传文件:
```
File file = new File("本地文件路径");
InputStream input = new FileInputStream(file);
FTPUtil.uploadFile("上传目录", "上传的文件名", input);
```
下载文件:
```
OutputStream output = new FileOutputStream(new File("本地文件路径"));
FTPUtil.downloadFile("下载目录", "下载的文件名", output);
```
删除文件:
```
FTPUtil.deleteFile("删除目录", "删除的文件名");
```
阅读全文