java ftp工具类
时间: 2023-08-15 08:08:52 浏览: 35
以下是一个简单的 Java FTP 工具类的示例代码,它使用 Apache Commons Net 库实现 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 String host;
private int port;
private String username;
private String password;
private FTPClient ftpClient;
public FtpUtil(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
ftpClient = new FTPClient();
}
public void connect() throws SocketException, IOException {
ftpClient.connect(host, port);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
ftpClient.disconnect();
throw new IOException("FTP server refused connection.");
}
ftpClient.login(username, password);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
}
public void disconnect() throws IOException {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
public InputStream downloadFile(String remoteFilePath) throws IOException {
return ftpClient.retrieveFileStream(remoteFilePath);
}
public OutputStream uploadFile(String remoteFilePath) throws IOException {
return ftpClient.storeFileStream(remoteFilePath);
}
}
```
使用示例:
```
FtpUtil ftp = new FtpUtil("ftp.example.com", 21, "username", "password");
ftp.connect();
InputStream inputStream = ftp.downloadFile("/remote/path/file.txt");
OutputStream outputStream = ftp.uploadFile("/remote/path/newfile.txt");
// 处理输入输出流
ftp.disconnect();
```