(原创)FTP操作类

时间:2020-11-30 14:11:05


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;
 }

 /*
  * getter & setter
  */
 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();
  }
 }

 /**
  * 关闭连接
  */
 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[i].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();
 }

}