通过xftp可以看到目标服务器上面的资源如下:
第一步:导入ftp依赖:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.7</version> <!-- 使用最新版本 -->
</dependency>
首先是通过原生代码来操作:
这里有个坑:如果是匿名登录,账号密码还是要的String username = "anonymous"
即可,密码随意,直接上代码:
下载文件操作:
import com.example.demo.test1.utils.FtpUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class test8 {
public static void main(String[] args) throws Exception {
String server = "ftp.ncbi.nlm.nih.gov";
int port = 21;
String username = "anonymous";
String password = "your_password";
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server, port);
ftpClient.login(username, password);
String remoteFilePath = "/pubmed/updatefiles/pubmed24n1220.xml.gz";
String localFilePath = "D:\\BaiduNetdiskDownload\\pubmed24n1220.xml.gz";
//设置本地被动模式
ftpClient.enterLocalPassiveMode();
ftpClient.setControlEncoding("UTF-8");
// 设置二进制文件类型
//ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
try {
// 创建本地文件输出流
OutputStream outputStream = new FileOutputStream(localFilePath);
// 从 FTP 服务器下载文件
boolean success = ftpClient.retrieveFile(remoteFilePath, outputStream);
if (success) {
System.out.println("File downloaded successfully.");
} else {
System.out.println("File download failed.");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭 FTP 连接
ftpClient.logout();
ftpClient.disconnect();
}
}
}
这里的远端路径和需要下载的本地路径我都提前把文件名拼上去了,根据需要可以动态拼接:下载结果:
查看文件目录操作:查看/pubmed下的目录:
public class test6 {
public static void main(String[] args) throws Exception{
String server <