java上传ftp文件代码
时间: 2023-08-26 16:05:08 浏览: 106
以下是一个简单的Java上传文件到FTP服务器的示例代码:
```java
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.*;
public class FTPUploader {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "ftp_username";
String password = "ftp_password";
String remoteDir = "/upload";
String localFilePath = "/path/to/local/file.txt";
String remoteFileName = "file.txt";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
File localFile = new File(localFilePath);
InputStream inputStream = new FileInputStream(localFile);
ftpClient.changeWorkingDirectory(remoteDir);
boolean uploaded = ftpClient.storeFile(remoteFileName, inputStream);
inputStream.close();
ftpClient.logout();
ftpClient.disconnect();
if (uploaded) {
System.out.println("File uploaded successfully.");
} else {
System.out.println("File upload failed.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
需要注意的是,需要使用Apache Commons Net库来实现FTP客户端功能。此外,需要根据实际情况修改服务器地址、端口、用户名、密码、远程目录、本地文件路径以及远程文件名等参数。
阅读全文