java上传文件到远程服务器
时间: 2023-09-02 09:08:41 浏览: 72
Java如何实现上传文件到服务器指定目录
5星 · 资源好评率100%
你好,关于Java上传文件到远程服务器的问题,可以使用FTP协议来实现。以下是一个简单的示例:
```java
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
public class FileUploader {
private String server;
private int port;
private String username;
private String password;
public FileUploader(String server, int port, String username, String password) {
this.server = server;
this.port = port;
this.username = username;
this.password = password;
}
public boolean uploadFile(File file, String remoteDir) {
FTPClient ftp = new FTPClient();
try {
ftp.connect(server, port);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
return false;
}
boolean success = ftp.login(username, password);
if (!success) {
System.err.println("Could not login to the FTP server");
return false;
}
success = ftp.changeWorkingDirectory(remoteDir);
if (!success) {
System.err.println("Remote directory does not exist on the FTP server");
return false;
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
FileInputStream in = new FileInputStream(file);
success = ftp.storeFile(file.getName(), in);
in.close();
if (!success) {
System.err.println("Could not upload file to the FTP server");
return false;
}
ftp.logout();
ftp.disconnect();
return true;
} catch (IOException ex) {
System.err.println("IOException: " + ex.getMessage());
return false;
}
}
}
```
以上代码中的 `FileUploader` 类可以用于上传本地文件到FTP服务器。在使用时,可以通过以下代码来上传文件:
```java
File file = new File("path/to/local/file");
String remoteDir = "/path/on/ftp/server";
FileUploader uploader = new FileUploader("ftp.server.com", 21, "username", "password");
boolean success = uploader.uploadFile(file, remoteDir);
```
其中 `server`、`port`、`username`、`password` 表示FTP服务器的地址、端口、登录账号和密码,`file` 和 `remoteDir` 分别表示要上传的本地文件和远程目录。
希望能帮到你。
阅读全文