java ftp工具类(图片上传、下载、重命名、移动文件夹、删除文件)

这个工具类没有进行很好的封装,如果想封装可以自己去封装加工一下,还用这个工具类里面的路径是需要自己替换的。

public class FtpUtil {

   /*
    *@Description: 获取ftp连接
    *@param host        服务器地址
    *@param port        端口号
    *@param username    用户名
    *@param password    密码
    *@return:           ftp连接
    *@Author:  William
    *@Date:  2019/5/20 10:21
    */
   public static FTPClient getConnect(String host, int port, String username, String password){
      FTPClient ftp = new FTPClient();
      int reply;
      try {
         ftp.connect(host, port);// 连接FTP服务器
         // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
         ftp.login(username, password);// 登录
         reply = ftp.getReplyCode();
         if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return null;
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
      return ftp;
   }

   /*
    *@Description: 断开ftp连接
    *@param ftp连接
    *@Author:  William
    *@Date:  2019/5/20 10:39
    */
   public static void disConnect(FTPClient ftp){
      if (ftp.isConnected()) {
         try {
            ftp.disconnect();
         } catch (IOException ioe) {
         }
      }
   }

    /* Description: 向FTP服务器上传文件
     * @param host FTP服务器ip
     * @param port FTP服务器端口
     * @param username FTP登录账号
     * @param password FTP登录密码
     * @param basePath FTP服务器基础目录,/home/ftpuser/images
     * @param filePath FTP服务器文件存放路径。例如分日期存放:/2018/05/28。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名
     * @param input 输入流
     * @return 成功返回true,否则返回false
     */
   public static boolean uploadFile(String host, int port, String username, String password, String basePath, String filePath, String filename, InputStream input) {
      boolean result = false;
      FTPClient ftp = getConnect(host,port,username,password);
      try {
         if(ftp == null){
            return result;
         }
         //切换到上传目录
         if (!ftp.changeWorkingDirectory(basePath+filePath)) {
            //如果目录不存在创建目录
            String[] dirs = filePath.split("/");
            String tempPath = basePath;
            for (String dir : dirs) {
               if (null == dir || "".equals(dir)) continue;
                  tempPath += "/" + dir;
                  if (!ftp.changeWorkingDirectory(tempPath)) {
                     if (!ftp.makeDirectory(tempPath)) {
                        return result;
                  } else {
                     ftp.changeWorkingDirectory(tempPath);
                  }
               }
            }
         }
         //设置为被动模式
         ftp.enterLocalPassiveMode();
         //设置上传文件的类型为二进制类型
         ftp.setFileType(FTP.BINARY_FILE_TYPE);
         //上传文件
         if (!ftp.storeFile(filename, input)) {
            return result;
         }
         input.close();
         ftp.logout();
         result = true;
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         disConnect(ftp);
      }
      return result;
   }

   
   /** 
    * Description: 从FTP服务器下载文件 
    * @param host FTP服务器hostname 
    * @param port FTP服务器端口 
    * @param username FTP登录账号 
    * @param password FTP登录密码 
    * @param remotePath FTP服务器上的相对路径 
    * @param fileName 要下载的文件名 
    * @param localPath 下载后保存到本地的路径 
    * @return 
    */  
   public static boolean downloadFile(String host, int port, String username, String password, String remotePath, String fileName, String localPath) {
      boolean result = false;
      FTPClient ftp = getConnect(host,port,username,password);
      try {
         if(ftp == null){
            return result;
         }
         ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
         try {
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
               if (ff.getName().equals(fileName)) {
                  File localFile = new File(localPath + "/" + ff.getName());
                  OutputStream is = new FileOutputStream(localFile);
                  ftp.retrieveFile(ff.getName(), is);
                  is.close();
               }
            }
            ftp.logout();
            result = true;
         } catch (Exception e) {
            e.printStackTrace();
         }


      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         disConnect(ftp);
      }
      return result;
   }

   /*
    *@Description: 删除文件夹中的文件
    *@param remotePath 要删除的文件夹  /home/ftpuser/www/img/teacherQualification/2015/01/22
    *@return:
    *@Author:  William
    *@Date:  2019/5/20 13:29
    */
   public static boolean delFolder(String host, int port, String username, String password,String uploadPath, String remotePath){
        boolean result = false;
        if(!remotePath.contains(uploadPath)) {
           remotePath = uploadPath+"/"+remotePath ;
      }
        FTPClient ftp = getConnect(host,port,username,password);
        try {
            if(ftp == null){
                return result;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                //循环删除文件
              delFile(host,port,username,password,remotePath+"/"+ff.getName());
            }
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            disConnect(ftp);
        }
        return result;
    }

   /*
    *@Description: 删除文件
    *@param filePath 删除文件的物理路径  /usr/local/www/img/....
    * @param host FTP服务器hostname
    * @param port FTP服务器端口
    * @param username FTP登录账号
    * @param password FTP登录密码
    *@return:
    *@Author:  William
    *@Date:  2019/5/20 10:51
    */
    public static boolean delFile(String host, int port, String username, String password, String filePath){
      boolean result = false;
      FTPClient ftp = getConnect(host,port,username,password);
      if(ftp == null || StringUtils.isEmpty(filePath) ){
         return result;
      }
      try {
         ftp.deleteFile(filePath);
         ftp.logout();
         result = true;
      } catch (IOException e) {
         e.printStackTrace();
      }finally {
         disConnect(ftp);
      }
      return result;
   }


   /*
    *@Description: 重命名文件(原路径和新路径必须在同一个文件夹)
    * @param host FTP服务器hostname
    * @param port FTP服务器端口
    * @param username FTP登录账号
    * @param password FTP登录密码
    *@param filePath  文件路径
    *@param newPath   文件新路径
    *@return:
    *@Author:  William
    *@Date:  2019/5/20 11:16
    */
    public static boolean changeFileName(String host, int port, String username, String password, String filePath,String newPath){
      boolean result = false;
      FTPClient ftp = getConnect(host,port,username,password);
      if(ftp == null || StringUtils.isEmpty(filePath) ){
         return result;
      }
      try {
          ftp.changeWorkingDirectory(filePath.substring(0,filePath.lastIndexOf("/")));
         ftp.rename(filePath,newPath);
         ftp.logout();
         result = true;
      } catch (IOException e) {
         e.printStackTrace();
      }finally {
         disConnect(ftp);
      }
      return result;
   }


   /**
    * @param host
      * @param port
      * @param username
      * @param password
      * @param filePath 原路径/home/ftpuser/www/img/teacherQualification/lesosnImg/106/lessonDetail/temp/0750bd4c9d91906418db886b2e659fe.jpg
      * @param newPath  目标路径/home/ftpuser/www/img/teacherQualification/lesosnImg/106/lessonDetail/img/0750bd4c9d91906418db886b2e659fe.jpg
    * @return boolean
    * @author: lijian
    * @description: 移动文件
    * @date 2019/5/20 13:41
    */
     public static boolean changeFilePath(String host, int port, String username, String password, String filePath,String newPath){
         boolean result = false;
         FTPClient ftp = getConnect(host,port,username,password);
         if(ftp == null || StringUtils.isEmpty(filePath) ){
             return result;
         }
         try {
          ftp.enterLocalPassiveMode();
          ftp.setFileType(FTP.BINARY_FILE_TYPE);
          InputStream inputStream = ftp.retrieveFileStream(new String(filePath.getBytes("UTF-8"), "ISO-8859-1"));
          //获取上传文件的文件名
          String uploadFileName = newPath.substring(newPath.lastIndexOf("/")+1,newPath.length());
          //获取上传路径
          String uploadPath  = newPath.substring(0,newPath.lastIndexOf("/"));
          String fileTempPath = uploadPath.substring(uploadPath.lastIndexOf("img/")+4,uploadPath.length());
          uploadFile(host, port, username, password,"/home/ftpuser/www/img",fileTempPath,uploadFileName,inputStream);
          ftp.deleteFile(filePath);
          inputStream.close();
          ftp.logout();
          result = true;
         } catch (IOException e) {
             e.printStackTrace();
         }finally {
             disConnect(ftp);
         }
         return result;
     }


   public static void main(String[] args) {

    
   }
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
public class FTPUtil { private FTPClient ftpClient=null; private boolean result = false; private FileInputStream fis; String ftpHost = "10.16.111.111"; String port = 21 String ftpUserName = "ftpuser11; String ftpPassword = "1234561"; /** * 登录服务器 * @param ftpInfo * @return * @throws IOException */ public FTPClient login() throws IOException { ftpClient = new FTPClient(); ftpClient.connect(ftpHost); boolean login = ftpClient.login(ftpUserName,ftpPassword); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } if(login){ System.out.println("ftp连接成功!"); }else{ System.out.println("ftp连接失败!"); } //ftpClient.setControlEncoding("GBK"); return ftpClient; } /** * 字符串作为文件上传指定目录 下 * @param content 源字符串 * @param uploadDir 上传目录 * @param ftpFileName 上传文件名称 * @throws Exception */ public void ftpUploadByText(String content ,String uploadDir,String ftpFileName) throws Exception{ try { ftpClient = this.login(); //创建目录 createDir(ftpClient,uploadDir); // 设置上传目录 这个也应该用配置文件读取 ftpClient.changeWorkingDirectory(uploadDir); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); String fileName = new String(ftpFileName.getBytes("GBK"),"iso-8859-1"); OutputStream os = ftpClient.storeFileStream(fileName); byte[] bytes = content.getBytes(); os.write(bytes); os.flush(); os.close(); } catch (Exception e) { ftpClient.disconnect(); ftpClient = null; e.printStackTrace(); throw e; }finally{ ftpClient.disconnect(); ftpClient = null; } } /** * 移动文件 * @param ftpInfo * @return * @throws Exception */ public boolean moveFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.moveFile(ftpClient, ftpInfo.getChangeWorkingDirectoryPath(), ftpInfo.getFilePath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 删除文件 * @param ftpInfo * @return * @throws Exception */ public boolean deleteFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.deleteByFolder(ftpClient, ftpInfo.getChangeWorkingDirectoryPath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 实现文件移动,这里做的是一个文件夹下的所有内容移动到新的文件, * 如果要做指定文件移动,加个判断判断文件名 * 如果不需要移动,只是需要文件重命名,可以使用ftp.rename(oleName,newName) * @param ftp * @param oldPath * @param newPath * @return */ public boolean moveFile(FTPClient ftp,String oldPath,String newPath){ boolean flag = false; try { ftp.changeWorkingDirectory(oldPath); ftp.enterLocalPassiveMode(); //获取文件数组 FTPFile[] files = ftp.listFiles(); //新文件夹不存在则创建 if(!ftp.changeWorkingDirectory(newPath)){ ftp.makeDirectory(newPath); } //回到原有工作目录 ftp.changeWorkingDirectory(oldPath); for (FTPFile file : files) { if(file.isDirectory()) { moveFile(ftp,oldPath+file.getName()+"/" ,newPath+file.getName()+"/"); }else{ //转存目录 flag = ftp.rename(oldPath+new String(file.getName().getBytes("GBK"),"ISO-8859-1"), newPath+"/"+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } if(flag){ System.out.println(file.getName()+"移动成功"); }else{ System.out.println(file.getName()+"移动失败"); } } ftp.removeDirectory(new String(oldPath.getBytes("GBK"),"ISO-8859-1")); } catch (Exception e) { e.printStackTrace(); System.out.println("移动文件失败"); } return flag; } /** * 删除FTP上指定文件夹文件及其子文件方法,添加了对中文目录的支持 * @param ftp FTPClient对象 * @param FtpFolder 需要删除文件夹 * @return */ public boolean deleteByFolder(FTPClient ftp,String FtpFolder){ boolean flag = false; try { ftp.changeWorkingDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); ftp.enterLocalPassiveMode(); FTPFile[] files = ftp.listFiles(); for (FTPFile file : files) { //判断为文件删除 if(file.isFile()){ ftp.deleteFile(FtpFolder+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } //判断是文件夹 if(file.isDirectory()){ String childPath = FtpFolder +file.getName()+ "/"; //递归删除文件夹 deleteByFolder(ftp,childPath); } } //循环完成后删除文件夹 flag = ftp.removeDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); if(flag){ System.out.println(FtpFolder+"文件夹删除成功"); }else{ System.out.println(FtpFolder+"文件夹删除成功"); } } catch (Exception e) { e.printStackTrace(); System.out.println("删除失败"); } return flag; } /** * 创建目录 * @param createpath * @param sftp */ public void createDir(FTPClient ftpClient,String createpath) throws Exception { try { if(ftpClient.changeWorkingDirectory(createpath)) { return; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if(!ftpClient.changeWorkingDirectory(filePath.toString())) { ftpClient.makeDirectory(filePath.toString()); ftpClient.changeWorkingDirectory(filePath.toString()); } } ftpClient.changeWorkingDirectory(createpath); }catch (Exception e) { e.printStackTrace(); throw new Exception("创建路径错误:" + createpath); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值