java ftp文件上传
时间: 2023-06-30 22:25:48 浏览: 125
你可以使用Java中提供的FTPClient类来实现FTP文件上传,具体步骤如下:
1. 创建FTPClient对象并连接FTP服务器
```java
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftpServer, port);
ftpClient.login(username, password);
```
2. 设置上传文件的类型为二进制
```java
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
```
3. 切换到上传文件的目录
```java
ftpClient.changeWorkingDirectory(remoteDirectory);
```
4. 上传文件
```java
File file = new File(localFilePath);
InputStream inputStream = new FileInputStream(file);
ftpClient.storeFile(remoteFileName, inputStream);
inputStream.close();
```
5. 关闭连接
```java
ftpClient.logout();
ftpClient.disconnect();
```
完整的代码如下:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FTPFileUploadDemo {
public static void main(String[] args) throws IOException {
String ftpServer = "ftp.example.com";
int port = 21;
String username = "username";
String password = "password";
String remoteDirectory = "/remote/directory";
String remoteFileName = "remote_file_name";
String localFilePath = "local_file_path";
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftpServer, port);
ftpClient.login(username, password);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.changeWorkingDirectory(remoteDirectory);
File file = new File(localFilePath);
InputStream inputStream = new FileInputStream(file);
ftpClient.storeFile(remoteFileName, inputStream);
inputStream.close();
ftpClient.logout();
ftpClient.disconnect();
}
}
```
注意,这里使用了Apache Commons Net库中的FTPClient类,需要添加相关依赖。
阅读全文