设为首页 收藏本站
查看: 760|回复: 0

[经验分享] Java_util_ftp_operation

[复制链接]

尚未签到

发表于 2016-6-8 10:55:37 | 显示全部楼层 |阅读模式
 
/**
*FTP操作类
*/
public class FTPTools {
 private String uid;
 private String pwd;
 private String hostname;
 
 private boolean binaryTransfer = true;
 private int port = 21;
 
 public FTPTools( String uid, String pwd, String hostname) {
  this.uid = uid;
  this.pwd = pwd;
  this.hostname = hostname;
 }
 public FTPTools( String uid, String pwd, String hostname, int port) {
  this.uid = uid;
  this.pwd = pwd;
  this.hostname = hostname;
  this.port = port;
 }
 
 public boolean isBinaryTransfer() {
  return binaryTransfer;
 }
 public void setBinaryTransfer(boolean binaryTransfer) {
  this.binaryTransfer = binaryTransfer;
 }
 
 public int getPort() {
  return port;
 }
 public  void setPort(int port) {
  this.port = port;
 }
 
 private FTPClient ftpClient = null;
 private SimpleDateFormat dateFormat = new SimpleDateFormat(
   "yyyy-MM-dd hh:mm");
 
 private final String[] FILE_TYPES = { "文件", "目录", "符号链接", "未知类型" };
 
 /**
  * 设置FTP客服端的配置--一般可以不设置
  * @return
  */
 private FTPClientConfig getFtpConfig() {
  FTPClientConfig ftpConfig = new FTPClientConfig(
    FTPClientConfig.SYST_UNIX);
  ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
  return ftpConfig;
 }
 
 /**
  * 连接到服务器
  * @throws IOException
  */
 public void openConnect() {
  int reply;
  try {
   // setArg(configFile);
   ftpClient = new FTPClient();
   ftpClient.setDefaultPort(port);
   ftpClient.configure(getFtpConfig());
   ftpClient.connect(hostname);
   ftpClient.login(uid, pwd);
   ftpClient.setControlEncoding("GB18030");
   System.out.print(ftpClient.getReplyString());
   reply = ftpClient.getReplyCode();
 
   if (!FTPReply.isPositiveCompletion(reply)) {
    ftpClient.disconnect();
    // user.writeLog("【FTPTools】:FTP server refused connection.");
    System.out.println("【FTPTools】:FTP server refused connection.");
   } else {
    if (ftpClient.login(uid, pwd)) {
     // 设置为passive模式
     ftpClient.enterLocalPassiveMode();
    }
    // user.writeLog("【FTPTools】:登录ftp服务器[" + hostname+ "]成功");
    System.out.println("【FTPTools】:登录ftp服务器[" + hostname + "]成功");
    System.out.println("【FTPTools】:当前目录为"
      + ftpClient.printWorkingDirectory());
    // user.writeLog("【FTPTools】:当前目录为" +
    // ftpClient.printWorkingDirectory());
   }
  } catch (Exception e) {
   // user.writeLog("【FTPTools】:登录ftp服务器[" + hostname + "]失败");
   System.out.println("【FTPTools】:登录ftp服务器[" + hostname + "]失败");
   e.printStackTrace();
  }
 }
 
  /**
     * 关闭链接 实现1
     */
    public void close()
    {
     try
     {
         if(ftpClient!=null&&ftpClient.serverIsOpen())
          ftpClient.closeServer();
     }catch(Exception e){e.printStackTrace();}
    }
 
 /**
  * 关闭连接  实现2
  */
 public void closeConnect() {
  try {
   if (ftpClient != null) {
    ftpClient.logout();
    System.out.print(ftpClient.getReplyString());
    ftpClient.disconnect();
    // user.writeLog("【FTPTools】:断开ftp服务器[" + hostname + "]成功");
    System.out.println("【FTPTools】:断开ftp服务器[" + hostname + "]成功");
   } else {
    System.out.println("【FTPTools】:已经断开ftp服务器[" + hostname + "]");
    // user.writeLog("【FTPTools】:已经断开ftp服务器[" + hostname + "]");
   }
 
  } catch (Exception e) {
   e.printStackTrace();
   // user.writeLog("【FTPTools】:断开ftp服务器[" + hostname + "]失败");
   System.out.println("【FTPTools】:断开ftp服务器[" + hostname + "]失败");
  }
 }
 
 /**
  * 进入到服务器的某个目录下
  * @param directory
  */
 public  void changeWorkingDirectory(String directory) {
  try {
 
   if (ftpClient == null) {
    openConnect();
   }
   ftpClient.changeWorkingDirectory(directory);
   System.out.print(ftpClient.getReplyString());
   System.out.println("【FTPTools】:进入目录" + directory);
   System.out.println("【FTPTools】:当前目录为"
     + ftpClient.printWorkingDirectory());
   // user.writeLog("【FTPTools】:当前目录为" +
   // ftpClient.printWorkingDirectory());
   // user.writeLog(ftpClient.getReplyString());
   // user.writeLog("【FTPTools】:进入目录" + directory);
  } catch (IOException ioe) {
   ioe.printStackTrace();
   // user.writeLog(ioe);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 /**
  * 返回到上一层目录
  */
 public  void changeToParentDirectory() {
  try {
   if (ftpClient == null) {
    openConnect();
   }
   ftpClient.changeToParentDirectory();
   System.out.print(ftpClient.getReplyString());
   System.out.println("【FTPTools】:返回至上层目录");
   System.out.println("【FTPTools】:当前目录为"
     + ftpClient.printWorkingDirectory());
   // user.writeLog("【FTPTools】:当前目录为" +
   // ftpClient.printWorkingDirectory());
   // user.writeLog(ftpClient.getReplyString());
   // user.writeLog("【FTPTools】:返回至上层目录");
  } catch (IOException ioe) {
   ioe.printStackTrace();
   // user.writeLog(ioe);
  }
 }
 
 /**
  * 列出服务器上所有文件及目录
  */
 public  void listAllRemoteFiles() {
  listRemoteFiles("*");
 }
 
 /**
  * 列出服务器上文件和目录
  * @param regStr --匹配的正则表达式  
  */
 // @SuppressWarnings("unchecked")
 @SuppressWarnings(value = { "unchecked" })
 public  void listRemoteFiles(String regStr) {
  checkConnect(ftpClient);
  try {
   FTPFile[] files = ftpClient.listFiles(regStr);
   System.out.print(ftpClient.getReplyString());
   if (files == null || files.length == 0) {
    System.out.println("【FTPTools】:There has not any file!");
    // user.writeLog("【FTPTools】:There has not any file!");
   } else {
    TreeSet<FTPFile> fileTree = new TreeSet(new Comparator() {
     // 先按照文件的类型排序(倒排),然后按文件名顺序排序
     public int compare(Object objFile1, Object objFile2) {
      if (objFile1 == null) {
       return -1;
      } else if (objFile2 == null) {
       return 1;
      } else {
       FTPFile file1 = (FTPFile) objFile1;
       FTPFile file2 = (FTPFile) objFile2;
       if (file1.getType() != file2.getType()) {
        return file2.getType() - file1.getType();
       } else {
        return file1.getName().compareTo(
          file2.getName());
       }
      }
     }
    });
    for (FTPFile file : files) {
     fileTree.add(file);
    }
    System.out.printf("%-35s%-10s%15s%15s/n", "名称", "类型", "修改日期",
      "大小");
    for (FTPFile file : fileTree) {
     System.out.printf("%-35s%-10s%15s%15s/n",
       iso8859togbk(file.getName()),
       FILE_TYPES[file.getType()],
       dateFormat.format(file.getTimestamp().getTime()),
       FileUtils.byteCountToDisplaySize(file.getSize()));
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
   //user.writeLog(e);
  }
 }
 
 /**
  * 设置传输文件的类型[文本文件或者二进制文件]
  * @param fileType --BINARY_FILE_TYPE、ASCII_FILE_TYPE
  */
 public  void setFileType(int fileType) {
  try {
   if (ftpClient == null) {
    openConnect();
   }
   ftpClient.setFileType(fileType);
  } catch (Exception e) {
   e.printStackTrace();
   // user.writeLog(e);
  }
 }
 
 /**
  * 转码[ISO-8859-1 -> GBK] 不同的平台需要不同的转码
  * @param obj
  * @return
  */
 private  String iso8859togbk(Object obj) {
  try {
   if (obj == null) {
    return "要转换的对象为null";
   } else {
    return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
   }
  } catch (Exception e) {
   return e.toString();
  }
 }
 
 /**
  * 删除文件
  */
 public  void deleteFile(String filename) {
  try {
   if (ftpClient == null) {
    openConnect();
   }
   ftpClient.deleteFile(filename);
   System.out.print(ftpClient.getReplyString());
   System.out.println("【FTPTools】:删除文件" + filename + "成功!");
   // user.writeLog(ftpClient.getReplyString());
   // user.writeLog("【FTPTools】:删除文件" + filename + "成功!");
  } catch (IOException ioe) {
   ioe.printStackTrace();
   // user.writeLog("【FTPTools】:删除文件" + filename + "失败!");
   System.out.println("【FTPTools】:删除文件" + filename + "失败!");
  }
 }
 
 /**
  * 重命名文件
  * @param oldFileName --原文件名
  * @param newFileName --新文件名
  */
 public  void renameFile(String oldFileName, String newFileName) {
  try {
   if (ftpClient == null) {
    openConnect();
   }
   ftpClient.rename(oldFileName, newFileName);
   System.out.print(ftpClient.getReplyString());
   System.out.println("【FTPTools】:将文件" + oldFileName + "重命名为"
     + newFileName);
   // user.writeLog(ftpClient.getReplyString());
   // user.writeLog("【FTPTools】:将文件" + oldFileName + "重命名为"+
   // newFileName);
  } catch (IOException ioe) {
   ioe.printStackTrace();
  }
 }
 
 /**
  * 上传文件
  * @param localFilePath --本地文件路径  
  * @param newFileName --新的文件名
  */
 public boolean uploadFile(String localFilePath, String localFileName,
   String remoteFilePath, String remoteFileName) {
  checkConnect(ftpClient);
  if (!localFilePath.endsWith("/")) {
   localFilePath += "/";
  }
  transferType(binaryTransfer);
  int reply;
 
  // 上传文件
  BufferedInputStream bis = null;
  try {
   ftpClient.changeWorkingDirectory(remoteFilePath);
   reply = ftpClient.getReplyCode();
   if (reply == 550) {
    ftpClient.makeDirectory(remoteFilePath);
    ftpClient.changeWorkingDirectory(remoteFilePath);
   }
 
   bis = new BufferedInputStream(new FileInputStream(localFilePath
     + localFileName));
   ftpClient.storeFile(remoteFileName, bis);
   System.out.println(ftpClient.getReplyString() + "【FTPTools】:上传文件" + localFilePath
     + localFileName + "成功!");
   return true;
  } catch (Exception e) {
   System.out.println("【FTPTools】:上传文件" + localFilePath
     + localFileName + "失败!");
   System.out.println(e.toString());
   return false;
  } finally {
   try {
    if (bis != null) {
     bis.close();
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * 下载文件
  * @param remoteFileName --服务器上的文件名  
  * @param localFileName  --本地文件名
  */
 public  boolean loadFile(String remoteFilePath, String remoteFileName,
   String localFilePath, String localFileName) {
  checkConnect(ftpClient);
  if (!remoteFilePath.endsWith("/")) {
   remoteFilePath += "/";
  }
  if (!localFilePath.endsWith("/")) {
   localFilePath += "/";
  }
  transferType(binaryTransfer);
  if (localFileName == "" || localFileName == null) {
   localFileName = remoteFileName;
  }
  // 下载文件
  BufferedOutputStream bos = null;
  try {
   if (remoteFilePath != "" && remoteFilePath != null) {
    changeWorkingDirectory(remoteFilePath);
   }
   System.out.println("【FTPTools】:开始下载文件到" + localFilePath + localFileName);
   //user.writeLog(ftpClient.getReplyString());
   if (isExist(remoteFileName)) {
    bos = new BufferedOutputStream(new FileOutputStream(
      localFilePath + localFileName));
    ftpClient.retrieveFile(remoteFileName, bos);
    System.out.print(ftpClient.getReplyString());
    System.out.println("【FTPTools】:下载文件" + remoteFilePath
      + remoteFileName + "成功!");
    return true;
   } else {
    System.out.println("【FTPTools】:文件" + remoteFilePath
      + remoteFileName + "不存在!");
    System.out.println("【FTPTools】:下载文件" + remoteFilePath
      + remoteFileName + "失败!");
    return false;
   }
  } catch (Exception e) {
   System.out.println(ftpClient.getReplyString() +"【FTPTools】:下载文件" + remoteFilePath
     + remoteFileName + "失败!");
   System.out.println(String.valueOf(e));
   return false;
  } finally {
   try {
    if (bos != null)
     bos.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * 设置文件传输类型
  * @param binaryTransfer
  * @throws IOException
  */
 public  void transferType(boolean binaryTransfer) {
  try {
   if (binaryTransfer) {
    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
   } else {
    ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 /**
  * 检查远端文件是否存在
  * @param remoteFileName
  * @return
  */
 @SuppressWarnings("unchecked")
 public  boolean checkFileName(String remotePath, String remoteFileName) {
  checkConnect(ftpClient);
  changeWorkingDirectory(remotePath);
  boolean result = false;
  try {
   FTPFile[] files = ftpClient.listFiles("*");
   System.out.print(ftpClient.getReplyString());
   if (files == null || files.length == 0) {
    System.out.println("【FTPTools】:There has not any file!");
    //user.writeLog("【FTPTools】:There has not any file!");
   } else {
    TreeSet<FTPFile> fileTree = new TreeSet(new Comparator() {
     // 先按照文件的类型排序(倒排),然后按文件名顺序排序
     public int compare(Object objFile1, Object objFile2) {
      if (objFile1 == null) {
       return -1;
      } else if (objFile2 == null) {
       return 1;
      } else {
       FTPFile file1 = (FTPFile) objFile1;
       FTPFile file2 = (FTPFile) objFile2;
       if (file1.getType() != file2.getType()) {
        return file2.getType() - file1.getType();
       } else {
        return file1.getName().compareTo(
          file2.getName());
       }
      }
     }
    });
    for (FTPFile file : files) {
     fileTree.add(file);
    }
    for (FTPFile file : fileTree) {
     if (file.getName().equals(remoteFileName)) {
      result = true;
      break;
     }
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  changeToParentDirectory();
  return result;
 }
 
 /**
  * 检测文件或文件夹是否存在
  * @param fileName --文件或文件夹名称
  * @return
  */
 public  boolean isExist(String fileName) {
  checkConnect(ftpClient);
  boolean tmp = false;
  try {
   System.out.println("【FTPTools】:当前目录为"
     + ftpClient.printWorkingDirectory());
   // user.writeLog("【FTPTools】:当前目录为" +
   // ftpClient.printWorkingDirectory());
   String[] strs = ftpClient.listNames();
   for (int i = 0; i < strs.length; i++) {
    if (strs.equals(fileName)) {
     tmp = true;
    }
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
  return tmp;
 }
 
 public void checkConnect(){
  checkConnect(this.ftpClient);
 }
 
 private void checkConnect(FTPClient ftpClient) {
  if (ftpClient == null) {
   openConnect();
  } else {
   try {
    ftpClient.stat();
   } catch (IOException e) {
    try {
     ftpClient.setDefaultPort(port);
     ftpClient.configure(getFtpConfig());
     ftpClient.connect(hostname);
     ftpClient.login(uid, pwd);
     ftpClient.setControlEncoding("GB18030");
     System.out.print(ftpClient.getReplyString());
     int reply = ftpClient.getReplyCode();
 
     if (!FTPReply.isPositiveCompletion(reply)) {
      ftpClient.disconnect();
      // user.writeLog("【FTPTools】:FTP server refused connection.");
      System.out.println("【FTPTools】:FTP server refused connection.");
     } else {
      if (ftpClient.login(uid, pwd)) {
       // 设置为passive模式
       ftpClient.enterLocalPassiveMode();
      }
      // user.writeLog("【FTPTools】:登录ftp服务器[" + hostname+ "]成功");
      System.out.println("【FTPTools】:登录ftp服务器[" + hostname + "]成功");
      System.out.println("【FTPTools】:当前目录为"
        + ftpClient.printWorkingDirectory());
      // user.writeLog("【FTPTools】:当前目录为" +
      // ftpClient.printWorkingDirectory());
     }
    } catch (Exception e2) {
     // user.writeLog("【FTPTools】:登录ftp服务器[" + hostname + "]失败");
     System.out.println("【FTPTools】:登录ftp服务器[" + hostname + "]失败");
     e2.printStackTrace();
    }
   }
  }
 }
 
 /**
  * 测试
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  FTPTools ftp = new FTPTools( "aaaa", "bbbb",
    "127.0.0.1");
  ftp.loadFile("/test" , "temp.txt", "C:/" , "");
  ftp.closeConnect();
 }
}
 

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-227780-1-1.html 上篇帖子: ftp client的开源实现 下篇帖子: UNIX常用FTP命令
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表