温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java怎么实现文件上传下载至ftp服务器

发布时间:2021-04-15 14:10:14 来源:亿速云 阅读:186 作者:小新 栏目:编程语言

小编给大家分享一下java怎么实现文件上传下载至ftp服务器,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

以前做的一个项目,用到了文件上传下载至ftp服务器,现在对其进行一下复习,比较简单,一下就能看明白。
环境:首先,先安装ftp服务器,我是在win8本地用IIS配置的, 百度一下就可以找到安装文档。

1.在你的项目目录下建立ftp配置文件,目录如下图

java怎么实现文件上传下载至ftp服务器

01 ftpconfig.properties:

ftpIp=10.73.222.29
ftpPort=21
ftpUser=WP
ftpPwd=04143114wp
ftpRemotePath=d://share 

02 读取ftpconfig.properties中的具体内容的类:

 package com.java.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author wangpei
 * @version 创建时间:2017年5月6日 下午9:42:40 读取ftp文件的配置文件
 */
public class ReadFtpProperties {
  private InputStream is;
  private Properties properties;

  public ReadFtpProperties() {
    is = this.getClass().getResourceAsStream("/ftpconfig.properties");// 将配置文件读入输入流中
    properties = new Properties();
    try {
      properties.load(is);
    } catch (IOException e) {
      System.out.println("配置文件不存在..");
      e.printStackTrace();
    } finally {

      if (null != is) {

        try {
          is.close();
        } catch (IOException e) {
          System.out.println("关闭流失败..");
          e.printStackTrace();
        }
      }

    }

  }

  public String getIp() {// 获取ftp服务器的ip地址
    return properties.getProperty("ftpIp");

  }

  public String getPort() {// 获取ftp服务器的端口
    return properties.getProperty("ftpPort");

  }

  public String getUser() {// 获取ftp登录用户名
    return properties.getProperty("ftpUser");

  }

  public String getPwd() {// 获取ftp服务器的登录密码
    return properties.getProperty("ftpPwd");

  }

  public String getRemotePath() {// 获取ftp服务器的存放文件的目录
    return properties.getProperty("ftpRemotePath");

  }

}

03 文件上传下载的接口类

package com.java.web.service;

import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import com.java.core.util.ReadFtpProperties;


/**
 * @author wangpei
 * @version 创建时间:2017年5月6日 下午6:39:03 
 * 文件上传下载业务逻辑接口层
 */
public interface FtpService {
  /*
   * 登录至FTP
   */
  public boolean loginFTP(FTPClient client, ReadFtpProperties rfp);

  /*
   * 退出ftp
   */
  public boolean logout(FTPClient client);//

  /*
   * 上传文件到remotePath,其在ftp上的名字为inputStream
   */
  public boolean uploadFile(FTPClient client, String remotePath,
      String fileNewName, InputStream inputStream, ReadFtpProperties rfp);

  /*
   * 从目录remotePath,下载文件fileName
   */
  public InputStream downFileByFtp(FTPClient client, String remotePath,
      String fileName);

  /*
   * 删除ftp上的目录为pathName的文件
   */
  public boolean delFile(FTPClient client, String pathName);

}

04 文件上传下载的接口实现类

package com.java.web.service.serviceImpl;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import com.java.core.util.ReadFtpProperties;
import com.java.web.service.FtpService;

/**
 * @author wangpei
 * @version 创建时间:2017年5月6日 下午10:02:28 类说明
 */
public class FtpServiceImpl implements FtpService {

  public boolean loginFTP(FTPClient client, ReadFtpProperties rfp) {
    String ftpIp = rfp.getIp();
    String ftpPort = rfp.getPort();
    String ftpUser = rfp.getUser();
    String ftpPwd = rfp.getPwd();
    // String fgtpRemotePath = rfp.getRemotePath();
    boolean b = false;

    try {
      client.connect(ftpIp, Integer.parseInt(ftpPort));
    } catch (NumberFormatException e) {
      System.out.println("无法连接到ftp");
      return false;
    } catch (SocketException e) {
      System.out.println("无法连接到ftp");
      return false;
    } catch (IOException e) {
      System.out.println("无法连接到ftp");
      return false;
    }
    client.setControlEncoding("uft-8");
    try {
      b = client.login(ftpUser, ftpPwd);
    } catch (IOException e) {
      System.out.println("登录ftp出错");
      logout(client);// 退出/断开FTP服务器链接
      return false;
    }
    return b;

  }

  public boolean logout(FTPClient client) {
    boolean b = false;

    try {
      b = client.logout();// 退出登录
      client.disconnect();// 断开连接
    } catch (IOException e) {
      return false;
    }
    return b;

  }

  public boolean uploadFile(FTPClient client, String remotePath,
      String fileNewName, InputStream inputStream, ReadFtpProperties rfp) {
    boolean b = false;
    try {
      client.setFileType(FTPClient.BINARY_FILE_TYPE);
      client.enterLocalPassiveMode();
      if (remotePath != null && !"".equals(remotePath.trim())) {
        String[] pathes = remotePath.split("/");
        for (String onepath : pathes) {
          if (onepath == null || "".equals(onepath.trim())) {
            continue;
          }

          onepath = new String(onepath.getBytes("utf-8"),
              "iso-8859-1");
          System.out.println("onepath=" + onepath);
          if (!client.changeWorkingDirectory(onepath)) {
            client.makeDirectory(onepath);// 创建FTP服务器目录
            client.changeWorkingDirectory(onepath);// 改变FTP服务器目录
          } else {
            System.out.println("文件单路径");
          }
        }
      }
      b = client.storeFile(new String(fileNewName.getBytes("utf-8"),
          "iso-8859-1"), inputStream);
    } catch (UnsupportedEncodingException e) {
      return false;
    } catch (IOException e) {
      return false;
    }
    return b;
  }

  public InputStream downFileByFtp(FTPClient ftpClient, String remotePath,
      String fileName) {

    FTPFile[] fs;
    InputStream is = null;
    try {
      // 设置被动模式
      ftpClient.enterLocalPassiveMode();
      // 设置以二进制流的方式传输
      ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
      // 设置编辑格式
      ftpClient.setControlEncoding("utf-8");

      remotePath = remotePath.substring(0,
          remotePath.lastIndexOf(fileName));
      fs = ftpClient.listFiles(remotePath);// 递归目标目录
      for (FTPFile ff : fs) {
        if (ff.getName().equals(fileName)) {// 查找目标文件
          is = ftpClient.retrieveFileStream(new String(
              (remotePath + fileName).getBytes("utf-8"),
              "iso-8859-1"));
          break;
        }
      }

    } catch (IOException e) {

      e.printStackTrace();
    }
    return is;

  }

  public boolean delFile(FTPClient ftpClient, String pathName) {
    boolean b = false;

    try {
      b = ftpClient.deleteFile(pathName);

      return b;
    } catch (Exception e) {
      return false;
    } finally {
      logout(ftpClient);// 退出/断开FTP服务器链接
    }

  }

}

代码很好理解,看一遍应该就可以理解,在这儿就不具体分析了,主要看代码中的注释。

以上是“java怎么实现文件上传下载至ftp服务器”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI