java实现连接ftp服务器并上传文件到ftp
时间: 2023-12-22 10:05:23 浏览: 103
服务器的代码怎么写?
您好!以下是Java实现连接FTP服务器并上传文件到FTP服务器的代码示例:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FTPUploadDemo {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String pass = "password";
String remoteFilePath = "/upload/example.txt";
String localFilePath = "C:/example.txt";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FileInputStream inputStream = new FileInputStream(new File(localFilePath));
boolean done = ftpClient.storeFile(remoteFilePath, inputStream);
inputStream.close();
if (done) {
System.out.println("The file was uploaded successfully.");
}
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
```
请注意,这只是一个示例代码,您需要根据实际情况进行修改和调整。
阅读全文