栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

通过ftp4j实现FTP over TLS上传下载文件或文件夹(上传支持断点续传)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过ftp4j实现FTP over TLS上传下载文件或文件夹(上传支持断点续传)

前言:

ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能。可以将ftp4j嵌到你的Java应用中,来传输文件(包括上传和下载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括:通过 TCP/IP直接连接,通过FTP代理、HTTP代理、SOCKS4/4a代理和SOCKS5代理连接,通过SSL安全连接。

配置ftp4j的jar包和环境

jar包下载链接
链接:https://pan.baidu.com/s/15yumrZZWXgW_2EC0LSLgyA
提取码:22jf


我是将jar包放到在resources文件夹下的新建的lib文件夹下。

在pom.xml里的here在here里添加。


            com.andrew
            ftp4j
            1.7.2
            system
            ${project.basedir}/src/main/resources/lib/ftp4j-1.7.2.jar

ftp4j工具类
@Slf4j
public class TLSFTPUtils {

   FTPClient client = new FTPClient();

   SSLContext sslContext = null;

   TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {

      public void checkClientTrusted(X509Certificate[] chain,
                                     String authType) throws CertificateException {
         // TODO Auto-generated method stub

      }

      public void checkServerTrusted(X509Certificate[] chain,
                                     String authType) throws CertificateException {
         // TODO Auto-generated method stub

      }

      public X509Certificate[] getAcceptedIssuers() {
         // TODO Auto-generated method stub
         return null;
      }

   } };


   public boolean connect(String hostname, String username, String password)  {
      try {
         sslContext = SSLContext.getInstance("SSL");
      } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
         log.error("SSL");
         return false;
      }
      try {
         sslContext.init(null, trustManager, new SecureRandom());
      } catch (KeyManagementException e) {
         e.printStackTrace();
         log.error("init");
         return false;
      }
      SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
      client.setSSLSocketFactory(sslSocketFactory);
      client.setSecurity(FTPClient.SECURITY_FTPES);
      client.setPassive(true);//设置被动
      client.setType(FTPClient.TYPE_BINARY);
      client.setCharset("gbk");
      try {
         client.connect(hostname);
      } catch (IOException | FTPIllegalReplyException | FTPException e) {
         e.printStackTrace();
         log.error("connect");
         return false;
      }
      log.info("连接"+hostname+"成功!"+client.toString());
      try {
         client.login(username, password);
      } catch (IOException | FTPIllegalReplyException | FTPException e) {
         e.printStackTrace();
         log.error("login");
         return false;
      }
      log.info("登录"+hostname+"成功!"+client.toString());

      return true;
   }

   
   public void upload(String dir,boolean del, File... files) throws Exception {
      if (StringUtils.isEmpty(dir) || files == null || files.length==0) {
         return;
      }
      try {
         mkdirs(dir); // 创建文件夹
         for (File file : files) {
            if (file.isDirectory()) { // 上传目录
               uploadFolder(getURL(dir), file, del);
            } else {
               client.changeDirectory(dir);
               String current2 = client.currentDirectory();
               System.out.println(current2);
               FTPFile[] files2 = client.list();
               FTPFile remoteFtpFile=null;
               boolean flag=false;
               for (FTPFile ftpFile:files2){
                  if (ftpFile.getName().equals(file.getName())){
                     flag=true;
                     remoteFtpFile=ftpFile;
                     break;
                  }
               }
               if (flag){
                  System.out.println("断点续传");
                  long remote_file_size=remoteFtpFile.getSize();
                  client.upload(file,remote_file_size);
                  log.debug("AbstractFtpEndpointComponent  upload  continue upload file success");
               }else {
                  System.out.println("从0上传");
                  client.upload(file);
               }
            }
         }
      } finally {
//         logout();
      }
   }
   
   public void upload(String dir, File... files) throws Exception {   
      upload(dir, false, files);
   }
   
   public void upload(String dir, boolean del, String... paths)
           throws Exception {
      if (dir==null || paths == null || paths.length ==0) {
         return;
      }
      File[] files = new File[paths.length];
      for (int i = 0; i < paths.length; i++) {
         files[i] = new File(paths[i]);
      }
      upload(dir, del, files);
   }
   
   public void upload(String dir, String... paths) throws Exception {
      upload(dir, false, paths);
   }
   
   private void uploadFolder( URL parentUrl, File file,
                             boolean del) throws Exception {
      client.changeDirectory(parentUrl.getPath());
      String dir = file.getName(); // 当前目录名称
      URL url = getURL(parentUrl, dir);
      if (!exists(url.getPath())) { // 判断当前目录是否存在
         client.createDirectory(dir); // 创建目录
      }
      client.changeDirectory(dir);
      File[] files = file.listFiles(); // 获取当前文件夹所有文件及目录
      for (int i = 0; i < files.length; i++) {
         file = files[i];
         if (file.isDirectory()) { // 如果是目录,则递归上传
            uploadFolder( url, file, del);
         } else { // 如果是文件,直接上传
//            client.changeDirectory(url.getPath());
            String current2 = client.currentDirectory();
            System.out.println(current2);
            FTPFile[] files2 = client.list();
            FTPFile remoteFtpFile=null;
            boolean flag=false;
            for (FTPFile ftpFile:files2){
               if (ftpFile.getName().equals(file.getName())){
                  flag=true;
                  remoteFtpFile=ftpFile;
                  break;
               }
            }
            if (flag){
               System.out.println("断点续传");
               long remote_file_size=remoteFtpFile.getSize();
               client.upload(file,remote_file_size);
               log.debug("AbstractFtpEndpointComponent  upload  continue upload file success");

            }else {
               System.out.println("从0上传");
               client.upload(file);
            }
            if (del){ // 删除源文件
               file.delete();
            }
         }
      }
   }
   
   public void delete(String... dirs) throws Exception {
      if (dirs == null || dirs.length ==0) {
         return;
      }
      try {
         int type = -1;
         for (String dir : dirs) {
            client.changeDirectory("/"); // 切换至根目录
            type = getFileType(dir); // 获取当前类型
            if (type == 0) { // 删除文件
               client.deleteFile(dir);
            } else if (type == 1) { // 删除目录
               deleteFolder(client, getURL(dir));
            }
         }
      } finally {
//         logout();
      }
   }
   
   private void deleteFolder(FTPClient client, URL url) throws Exception {
      String path = url.getPath();
      client.changeDirectory(path);
      FTPFile[] files = client.list();
      String name = null;
      for (FTPFile file : files) {
         name = file.getName();
         // 排除隐藏目录
         if (".".equals(name) || "..".equals(name)) {
            continue;
         }
         if (file.getType() == FTPFile.TYPE_DIRECTORY) { // 递归删除子目录
            deleteFolder(client, getURL(url, file.getName()));
         } else if (file.getType() == FTPFile.TYPE_FILE) { // 删除文件
            client.deleteFile(file.getName());
         }
      }
      client.changeDirectoryUp();
      client.deleteDirectory(url.getPath()); // 删除当前目录
   }
   
   public void download(String localDir, String... dirs) throws Exception {
      if (dirs==null ||dirs.length ==0) {
         return;
      }
      try {
         File folder = new File(localDir);
         if (!folder.exists()) { // 如果本地文件夹不存在,则创建
            folder.mkdirs();
         }
         int type = -1;
         String localPath = null;
         for (String dir : dirs) {
            client.changeDirectory("/"); // 切换至根目录
            type = getFileType(dir); // 获取当前类型
            if (type == 0) { // 文件
               localPath = localDir + "/" + new File(dir).getName();
               client.download(dir, new File(localPath));
            } else if (type == 1) { // 目录
               downloadFolder(client, getURL(dir), localDir);
            }
         }
      } finally {
//         logout();
      }
   }
   
   private void downloadFolder(FTPClient client, URL url, String localDir)
           throws Exception {
      String path = url.getPath();
      client.changeDirectory(path);
      // 在本地创建当前下载的文件夹
      File folder = new File(localDir + "/" + new File(path).getName());
      if (!folder.exists()) {
         folder.mkdirs();
      }
      localDir = folder.getAbsolutePath();
      FTPFile[] files = client.list();
      String name = null;
      for (FTPFile file : files) {
         name = file.getName();
         // 排除隐藏目录
         if (".".equals(name) || "..".equals(name)) {
            continue;
         }
         if (file.getType() == FTPFile.TYPE_DIRECTORY) { // 递归下载子目录
            downloadFolder(client, getURL(url, file.getName()), localDir);
         } else if (file.getType() == FTPFile.TYPE_FILE) { // 下载文件
            client.download(name, new File(localDir + "/" + name));
         }
      }
      client.changeDirectoryUp();
   }

//   
//   public String[] list(String dir) throws Exception {
      FTPClient client = null;
//      try {
         client = getClient();
//         client.changeDirectory(dir);
//         String[] values = client.listNames();
//         if (values != null) {
//            // 将文件排序(忽略大小写)
//            Arrays.sort(values, String::compareToIgnoreCase);
//         }
//         return values;
//      } catch(FTPException fe) {
//         // 忽略文件夹不存在的情况
//         String mark = "code=550";
//         if (!fe.toString().contains(mark)) {
//            throw fe;
//         }
//      } finally {
//         logout();
//      }
//      return new String[0];
//   }


   
   private void mkdirs(String dir) throws Exception {
      if (dir == null || dir.equals("")) {
         return;
      }
      dir = FTPPathToolkit.formatPathFTP(dir);
      dir = dir.replace("//", "/");
      String[] dirs = dir.split("/");
      String path = "";
      for (int i = 0; i < dirs.length; i++) {
         path  +=  dirs[i] + "/";

         if (!isDirExist(path)) {
            client.createDirectory(path);// 创建目录
            client.changeDirectory(path);// 进入创建的目录
         }
      }
   }


   
   private URL getURL(URL url, String dir) throws Exception {
      String path = url.getPath();
      if (!path.endsWith("/") && !path.endsWith("//")) {
         path += "/";
      }
      dir = dir.replace("//", "/");
      if (dir.startsWith("/")) {
         dir = dir.substring(1);
      }
      path += dir;
      return new URL(url, path);
   }
   
   private URL getURL(String dir) throws Exception {
      if (dir.startsWith("/")) {
         dir = dir.substring(1);
      }
      return getURL(new URL("http://8.8.8.8"), dir);
   }

   
   private boolean exists(String dir) throws Exception {
      return getFileType(dir) != -1;

   }

   //检查目录是否存在
   private boolean isDirExist(String dir) {
      try {
         client.changeDirectory(dir);
      } catch (Exception e) {
         return false;
      }
      return true;
   }


   
   private int getFileType( String dir) {
      FTPFile[] files = null;
      try {
         files = client.list(dir);

      } catch (Exception e) {
         return -1;
      }
      if (files.length > 1) {
         return FTPFile.TYPE_DIRECTORY;
      } else if (files.length == 1) {
         FTPFile f = files[0];
         if (f.getType() == FTPFile.TYPE_DIRECTORY) {
            return FTPFile.TYPE_DIRECTORY;
         }
         String path = dir + "/" + f.getName();
         try {
            int len = client.list(path).length;
            if (len == 1) {
               return FTPFile.TYPE_DIRECTORY;
            } else {
               return FTPFile.TYPE_FILE;
            }
         } catch (Exception e) {
            return FTPFile.TYPE_FILE;
         }
      } else {
         try {
            client.changeDirectory(dir);
            client.changeDirectoryUp();
            return FTPFile.TYPE_DIRECTORY;
         } catch (Exception e) {
            return -1;
         }
      }
   }


   
   public void logout()  {
      if (client != null) {
         try {
            // 有些FTP服务器未实现此功能,若未实现则会出错
            client.logout(); // 退出登录
         } catch (Exception fe) {

         } finally {
            if (client.isConnected()) { // 断开连接
               try {
                  client.disconnect(true);
               } catch (IOException | FTPIllegalReplyException | FTPException e) {
                  e.printStackTrace();
                  System.out.println("退出异常");
               }
            }
         }
      }
   }


   
   public void disconnect() {
      if (client.isConnected()) {
         try {
            client.disconnect(true);
         } catch (IOException | FTPIllegalReplyException | FTPException e) {
            e.printStackTrace();
            System.out.println("退出异常");
         }
      }
   }

}
ftp4j工具类调用方式:
 TLSFTPUtils tlsftpUtils = new TLSFTPUtils();
 boolean loginFlag = tlsftpUtils.connect("103.10.4.144","FIH000001","dm1rbap1wicb"); //开启连接
 String path = "D:/Data/CameraLogTransfer/"
 File localDirTransfer = new File(path);
 File[] transferFiles = localDirTransfer.listFiles();  //文件列表
 tlsftpUtils.upload("/DebugLog/",transferFiles);  //传输文件或文件夹都可以,里面做啦判断。
 //下载操作一样,目录文件或文件夹都行,里面做了判断。
 ftpUtils.disconnect();  //关闭连接

顺便说说:
下载没做断点续传,但是你们可以模仿上传过程写。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/530735.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号