java使用ftp工具类
时间: 2023-08-31 22:05:14 浏览: 300
以下是一个使用Java FTP工具类的示例,其中包括连接到FTP服务器,上传和下载文件等操作。
```java
import java.io.*;
import org.apache.commons.net.ftp.*;
public class FtpUtil {
private static FTPClient ftpClient = new FTPClient();
/**
* 连接FTP服务器
*
* @param host 主机名
* @param port 端口号
* @param username 用户名
* @param password 密码
* @return 是否连接成功
*/
public static boolean connect(String host, int port, String username, String password) {
try {
ftpClient.connect(host, port);
ftpClient.login(username, password);
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 上传文件到FTP服务器
*
* @param localFile 本地文件路径
* @param remotePath 远程文件路径
* @param remoteFile 远程文件名
* @return 是否上传成功
*/
public static boolean upload(File localFile, String remotePath, String remoteFile) {
boolean result = false;
InputStream inputStream = null;
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
inputStream = new FileInputStream(localFile);
ftpClient.changeWorkingDirectory(remotePath);
result = ftpClient.storeFile(remoteFile, inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 从FTP服务器下载文件
*
* @param remotePath 远程文件路径
* @param remoteFile 远程文件名
* @param localPath 本地文件路径
* @param localFile 本地文件名
* @return 是否下载成功
*/
public static boolean download(String remotePath, String remoteFile, String localPath, String localFile) {
boolean result = false;
OutputStream outputStream = null;
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(remotePath);
outputStream = new FileOutputStream(new File(localPath + File.separator + localFile));
result = ftpClient.retrieveFile(remoteFile, outputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
```
使用示例:
```java
// 连接FTP服务器
boolean isConnected = FtpUtil.connect("ftp.example.com", 21, "username", "password");
// 上传文件
File localFile = new File("C:\\example.txt");
boolean isUploaded = FtpUtil.upload(localFile, "/remote/path", "example.txt");
// 下载文件
String localPath = "C:\\";
String localFile = "example.txt";
boolean isDownloaded = FtpUtil.download("/remote/path", "example.txt", localPath, localFile);
```
阅读全文