Java下载FTP服务器上的资源,附带FTP工具类

通过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 <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值