java获取ftp上传代码
时间: 2023-10-18 14:10:08 浏览: 98
以下是一个简单的 Java 代码示例,演示如何使用 Apache Commons Net 库上传文件到 FTP 服务器:
```
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;
public class FtpUploader {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String username = "username";
String password = "password";
String remotePath = "/upload/";
String localFilePath = "C:\\example\\file.txt";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(username, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FileInputStream inputStream = new FileInputStream(localFilePath);
String remoteFileName = localFilePath.substring(localFilePath.lastIndexOf("\\") + 1);
boolean uploaded = ftpClient.storeFile(remotePath + remoteFileName, inputStream);
inputStream.close();
if (uploaded) {
System.out.println("File uploaded successfully.");
} else {
System.out.println("File upload failed.");
}
} catch (IOException ex) {
System.out.println("Error occurred: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
```
在这个示例中,我们使用了 Apache Commons Net 库的 FTPClient 类来连接 FTP 服务器并上传文件。我们首先连接到 FTP 服务器,然后登录并设置传输模式为二进制。接下来,我们使用 FileInputStream 类打开本地文件并将其上传到指定的远程路径。最后,我们关闭文件流并断开与 FTP 服务器的连接。
阅读全文