FTPClient上传下载文件

本文介绍如何使用Java实现FTP文件的上传与下载功能,包括连接FTP服务器、登录、上传文件、下载文件等步骤。

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

需要com.springsource.org.apache.commons.net-1.4.1.jar和com.springsource.org.apache.oro-2.0.8.jar两个FTPClient的包

 public static void main(String[] args) {
   //上传文件
      FTPClient ftp = new FTPClient();  
      try {  
          int reply;  

         //url FTP服务器hostname ,port FTP服务器端口
          ftp.connect("172.0.0.1", 21);//连接FTP服务器  
          //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器

         //创建输入流   
          FileInputStream input = new FileInputStream("D:\\apache-tomcat-6.0.18\\webapps\\FTDMProject\\upload\\20130703\\test.txt");
          //username FTP登录账号、密码

         ftp.login("sa", "sa");//登录  
          reply = ftp.getReplyCode();
          if (!FTPReply.isPositiveCompletion(reply)) {  
              ftp.disconnect();  
          }  

          //FTP服务器保存目录
          ftp.changeWorkingDirectory("/ProjectMaterial/file/2013/7/3");  

         //上传到FTP服务器上的文件名,输入流
          ftp.storeFile("test", input);
          input.close();  
          ftp.logout();  
          System.out.println("ok");
      } catch (IOException e) {  
          e.printStackTrace();  
      } finally {  
          if (ftp.isConnected()) {  
              try {  
                  ftp.disconnect();  
              } catch (IOException ioe) {  
              }  
          }  
      }   

 }

public static void main(String[] args) {

//下载文件
     try{

        int port = 21;
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(ftpServer, port);
        ftpClient.login(loginName, password);

       //FTP服务器保存目录

        ftpClient.changeWorkingDirectory(filePath);

       /创建/输出流

        FileOutputStream fos = new FileOutputStream(downfile+fileName);

      //文件名,输出流

        ftpClient.retrieveFile(fileName, fos);

        fos.flush();
       fos.close();

     }catch(IOException e){

       e.printStackTrace();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值