ftpClient匿名用户

本文提供了一个使用Java实现FTP文件下载的示例代码。通过该示例,读者可以了解到如何建立FTP连接、更改工作目录、列出远程文件,并将文件下载到本地。此外,还介绍了错误处理的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果没有设置ftp用户可将username设为anonymous,密码为任意字符串



public static void main(String[] args) {
  /*
   * FTPUtil myFtp = new FTPUtil(); try { myFtp.connect("127.0.0.1", 21,
   * "ftp", "123456"); myFtp.download("t.txt", "G:/test.txt");
   * myFtp.disconnect(); } catch (IOException e) {
   * System.out.println("连接FTP出错:" + e.getMessage()); }
   */
  String result = FTPUtil.downFile("192.168.8.175", "admin", "admin", "batchsend", "D:/myFile/");
  System.out.println(result);
 }
 
 public static String downFile(String ipAddress, String username,
   String password, String remotePath, String targetPath) {
  FTPClient ftp = new FTPClient();
  try {
   int reply;
   ftp.connect(ipAddress);

   ftp.login(username, password);// 登录
   reply = ftp.getReplyCode();

   if (!FTPReply.isPositiveCompletion(reply)) {
    ftp.disconnect();
    return "connect error. code:" + reply;
   }
   if (StringUtils.isNotBlank(remotePath)) {
    boolean flag = ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
    if(flag == false) {
     return "remotePath error";
    }
   }

   FTPFile[] fs = ftp.listFiles();
   if (fs == null || fs.length == 0) {
    return "not find files";
   }
   /*
    * if(fs.length != 5) { return "files count error"; }  //包括文件夹
    */
   for (FTPFile ff : fs) {
    if (ff.isFile()) {
     File localFile = new File(targetPath + "/");
     if (!localFile.exists()) {
      localFile.mkdirs();
     }
     OutputStream is = new FileOutputStream(localFile + "/"
       + ff.getName());
     ftp.retrieveFile(ff.getName(), is);
     is.close();
    }
   }
   ftp.logout();
  } catch (IOException e) {
   e.printStackTrace();
   return "file transfer error";
  } finally {
   if (ftp.isConnected()) {
    try {
     ftp.disconnect();
    } catch (IOException ioe) {
    }
   }
  }
  return "success";
 }






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值