sun.net.ftp.FtpClient 实现简单上传下载

本文介绍如何使用sun.net.ftp.FtpClient类实现FTP文件上传和下载功能。包括建立连接、设置二进制传输模式、上传多个文件及下载指定路径下的文件等步骤。

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

sun.net.ftp.FtpClient 可以帮助我们进行一些简单的ftp客户端功能:下载、上传文件,但如遇到创建目录之类的就无能为力了,我们只好利用第三方源码。

1.文件的上传

System.out.println("开始建立连接");
   FtpClient ftpClient=new FtpClient(ip,Integer.valueOf(sock).intValue());
   ftpClient.login(username,pwd);
   ftpClient.binary();
   System.out.println("成功建立连接开始上传文件");
   for(int i=0;i<filename.length;i++){
    File f=new File(createfilepath+File.separator+filename[i]);
    System.out.println("开始上传文件:"+createfilepath+File.separator+filename[i]);
    if(!f.exists())continue;
    FileInputStream fis=new FileInputStream(f);
       TelnetOutputStream tos=ftpClient.put(uppath+File.separator+f.getName());
       byte[] bt=new byte[1024];
       int len=0;
       int lenTotal=0;
       while((len=fis.read(bt))!=-1) {
           lenTotal+=len;
           tos.write(bt,0,len);
       }
       System.out.println("成功上传文件:"+createfilepath+File.separator+filename[i]);
       tos.close();
       fis.close();
         }
         ftpClient.closeServer();

2.文件的下载

FtpClient ftpClient = new FtpClient(ip, Integer.valueOf(sock).intValue());
   ftpClient.login(username, pwd);
   BufferedReader reader = new BufferedReader(new InputStreamReader(ftpClient.nameList(downpath)));
   ArrayList<String> nameList = new ArrayList<String>();
   
   String s = "";
   while( (s = reader.readLine()) != null){
    if(s.indexOf(".xls")==-1 && s.indexOf(".dat")==-1)
     nameList.add(s);
   }
   
   for(String filename : nameList){
    File f = new File(filename);
    if(!f.isDirectory()){
     File fi = new File(downfilepath+File.separator+filename);
     RandomAccessFile getFile = new RandomAccessFile(fi, "rw");
     getFile.seek(0);
     TelnetInputStream ins = ftpClient.get(downpath+File.separator+filename);
     DataInputStream dins = new DataInputStream(ins);
     
     String ss = "";
     while((s = dins.readLine()) != null){
      getFile.writeBytes(ss);
     }
     ins.close();
     dins.close();
    }
   }
   ftpClient.closeServer();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值