记录一次FTP下载文件时ftpClient.listFiles(path)时size为0的解决方法

记录一次Linux系统下FTP下载文件时ftpClient.listFiles(path)时size为0的解决方法

最近一次项目做一个ftp服务器文件下载并导入数据库的功能,从其他大神博客处提供的ftp工具类开始处理(https://blog.csdn.net/wangmx1993328/article/details/82150290),本地windows系统搭建的ftp服务器下载导入一切正常,并可以同步更新ftp服务器文件,大神的工具类用起来真不错。开始测试linux下的ftp服务器时下载一直出现问题,在获取所有文件时结果一直为根目录下的一个子目录,因为是递归调用,最后结果取的目录是这样/download/download/download/...无限循环。
获取所有文件的方法

 public static List<String> loopServerPath(FTPClient ftpClient, String remotePath, List<String> relativePathList) {
        /**如果 FTP 连接已经关闭,或者连接无效,则直接返回*/
        if (!ftpClient.isConnected() || !ftpClient.isAvailable()) {
            System.out.println("ftp 连接已经关闭或者连接无效......");
            return relativePathList;
        }
        try {
            /**转移到FTP服务器根目录下的指定子目录
             * 1)&
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
`FTPClient` 是 Java 中用于操作 FTP 服务器的类,其中的 `listFiles` 方法用于获取 FTP 服务器上指定目录下的文件和子目录的列表。该方法返回一个 FTPFile 对象数组,其中包含指定目录中的所有文件和子目录。如果目录不存在或者不是一个目录,则该方法将返回空数组。以下是 `FTPClient` 中 `listFiles` 方法的示例代码: ```java import java.io.IOException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPListFilesExample { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String user = "username"; String password = "password"; String remoteDirPath = "/path/to/remote/directory"; FTPClient ftp = new FTPClient(); try { ftp.connect(server, port); int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("FTP server refused connection."); return; } boolean success = ftp.login(user, password); if (!success) { System.out.println("Could not login to the FTP server."); return; } ftp.enterLocalPassiveMode(); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); FTPFile[] files = ftp.listFiles(remoteDirPath); for (FTPFile file : files) { if (file.isFile()) { System.out.println("File: " + file.getName()); } else if (file.isDirectory()) { System.out.println("Directory: " + file.getName()); } } ftp.logout(); } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ex) { // do nothing } } } } } ``` 注意,需要使用 Apache Commons Net 库中的 `FTPClient` 类来实现 FTP 操作。该库可以从 Apache 网站上下载

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值