Skip to content

fzzf123/ALFTPTool

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 

Repository files navigation

ALFTPTool

package com.sinosoft.tool;import it.sauronsoftware.ftp4j.FTPClient;import it.sauronsoftware.ftp4j.FTPDataTransferListener;import it.sauronsoftware.ftp4j.FTPFile;import java.io.File;import java.net.URLDecoder;import java.util.Properties;/** * ftp工具 *  * @author ChengQi *  /public class ALFTPTool implements FTPDataTransferListener{  private String ip=""; private String port=""; private String userName=""; private String passWord=""; private String ftpPath="";  private String ftpType=""; private String fileName="";    public String getFtpType() {  return ftpType; } public void setFtpType(String ftpType) {  this.ftpType = ftpType; } public String getFileName() {  return fileName; } public void setFileName(String fileName) {  this.fileName = fileName; } public String getIp() {  return ip; } public void setIp(String ip) {  this.ip = ip; } public String getPort() {  return port; } public void setPort(String port) {  this.port = port; } public String getUserName() {  return userName; } public void setUserName(String userName) {  this.userName = userName; } public String getPassWord() {  return passWord; } public void setPassWord(String passWord) {  this.passWord = passWord; } protected FTPClient client = new FTPClient(); public static Properties ftpProperties = new Properties(); public static final String OVER_WRITE = "1"; public static final String CODE_TYPE = "UTF-8"; public static final int FILE_NOT_EXITS = -1; private static final String MyFtpListener = null; private static String basePath; boolean downLoan = false; // 下载标志 public static final String downLoadFtpType = "1"; // 上传标志 public static final String uploadFtpType = "2"; // static// {//  try//  {//   ftpProperties.load(FTPTool.class.getResourceAsStream("Alftp.properties"));//   if (ftpProperties.getProperty("overWrite") == null)//    ftpProperties.setProperty("overWrite", "0");////   basePath = ftpProperties.getProperty("path");//  }//  catch (Exception e)//  {//   e.printStackTrace();//   throw new FtpException(e);//  }// }  public ALFTPTool(){}  public ALFTPTool(String ftpType, String fileName) {  this.ftpType = ftpType;  this.fileName = fileName; }  public ALFTPTool( String ip,String port, String userName,String passWord, String ftpPath){  this.ip   = ip;  this.port = port;  this.userName = userName;  this.passWord = passWord;  this.ftpPath = ftpPath;   } public boolean connectpath(String path) {  try  {   client.changeDirectory("/"+path);   return true;  }  catch (Exception e)  {   e.printStackTrace();   return false;  } } /*  * 设置ftp主机  *   * @param host  / public void setFtpHost(String host) {  ftpProperties.setProperty("host", host); } /*  * 设置当前路径  / public void setFtpPath(String ftpPath) {  this.ftpPath = ftpPath; } /*  * 获取当前路径  / public String getFtpPath() {  return ftpPath; } /*  * 获取基准ftp路径  / public String getBaseFtpPath() {  return basePath; } /*  * 设置ftp 用户 密码  *   * @param user  * @param name  / public void setLogin(String user, String name) {  ftpProperties.setProperty("user", user);  ftpProperties.setProperty("password", name); } /*  * 设置是否覆写  *   * @param overWrite  / public void setOverWrite(String overWrite) {  ftpProperties.setProperty("overwrite", overWrite); }  /*  * 链接服务器  / public void connect() {  try  {   client.setPassive(true); // 主动被动方式连接ftp,如下载和上传出现阻塞问题,可尝试修改此值。   client.connect(ip,Integer.parseInt(port));   client.login(userName, passWord);   client.changeDirectory(ftpPath);   client.setType(FTPClient.TYPE_BINARY);    }  catch (Exception e)  {   e.printStackTrace();   throw new FtpException("连接ftp失败");  } }   /*    * 创建目录    *     * @param destDirName 目标目录名    * @return 目录创建成功返回true,否则返回false    /   public static boolean createDir(String destDirName)   {     File dir = new File(destDirName);     if (!destDirName.endsWith(File.separator))       destDirName = destDirName + File.separator;     // 创建单个目录     if (dir.mkdirs())     {       System.out.println("创建目录" + destDirName + "成功!");       return true;     } else     {       System.out.println("创建目录" + destDirName + "成功!");       return false;     }   } /*  * 下载文件  *   * @param path    ftp上的文件名称  *   * @param file    本地地址以及文件名  / public void downloadFile(String path, File file) {  try  {   client.download(path, file);  }  catch (Exception e)  {   throw new FtpException(e);  } } /*  * 下载文件夹  *   * @param path  * @param file  / public void downloadFolder(String path, File file) {  try  {   int type = isExist(path);   if (file.isFile())   {    throw new FtpException("所要的下载保存的地方是一个文件,无法保存!");   }   else   {    if (!file.exists())    {     boolean isTrue = file.mkdirs();     if (!isTrue)     {      throw new FtpException("创建本地文件夹失败!");     }    }    client.changeDirectory(client.currentDirectory() + "/" + path);   }   if (type == FTPFile.TYPE_FILE)   {    String fileName = file.getName();    fileName = URLDecoder.decode(fileName, this.CODE_TYPE);    client.download(path, new File(file.getPath() + File.separator + fileName));   }   else if (type == FTPFile.TYPE_DIRECTORY)   {    FTPFile[] ftpFIleList = client.list("");    if (ftpFIleList.length == 0)    {     client.changeDirectoryUp();     return;    }    for (int i = 2, n = ftpFIleList.length; i < n; i++)    {     FTPFile fTPFile = ftpFIleList[i];     if (fTPFile.getType() == fTPFile.TYPE_FILE)     {      client.download(client.currentDirectory() + "/" + fTPFile.getName(),        new File(file.getPath() + File.separator + URLDecoder.decode(fTPFile.getName(), this.CODE_TYPE)));      System.out.println("111" + client.currentDirectory() + "/" + fTPFile.getName());      System.out.println("222" + file.getPath() + File.separator + URLDecoder.decode(fTPFile.getName(), this.CODE_TYPE));     }     else if (fTPFile.getType() == fTPFile.TYPE_DIRECTORY)     {      downloadFolder(fTPFile.getName(), new File(file.getPath() + File.separator + URLDecoder.decode(fTPFile.getName(), this.CODE_TYPE)));     }    }    client.changeDirectoryUp();   }   // System.out.println("退出时 的 远程路径 = " + client.currentDirectory());  }  catch (Exception e)  {   throw new FtpException(e);  } } /*  * public void downloadTest(String remoteFileName, String localFolderPath) {  * int x = isExist(remoteFileName); MyFtpListener listener =  * MyFtpListener.instance(); File localFolder = new File(localFolderPath); if  * (localFolder.isFile()) { //throw new  * FTPRuntimeException("所要的下载保存的地方是一个文件,无法保存!"); } else { if  * (!localFolder.exists()) localFolder.mkdirs(); } if (x == FTPFile.TYPE_FILE)  * { String localfilepath = PathToolkit.formatPath4File(localFolderPath +  * File.separator + new File(remoteFileName).getName()); try { if (listener !=  * null) client.download(remoteFileName, new File(localfilepath), listener);  * else client.download(remoteFileName, new File(localfilepath)); } catch  * (Exception e) { // /throw new FTPRuntimeException(e); } } else { // throw  * new FTPRuntimeException("所要下载的文件" + remoteFileName + "不存在!"); } }  / /*  * 上传文件 支持上传文件夹下所有的子文件夹以及子文件  *   * @param file  / public void uploadFile(File file) {  if (file.isDirectory())  {   try   {//    client.createDirectory(URLEncoder.encode(file.getName(), this.CODE_TYPE));   }   catch (Exception e)   {    throw new FtpException(e);   }   File[] filelist = file.listFiles();   if (filelist == null)   {    try    {     client.changeDirectoryUp();    }    catch (Exception e)    {     throw new FtpException(e);    }    return;   }   try   {//    client.changeDirectory(client.currentDirectory() + "/" + URLEncoder.encode(file.getName(), this.CODE_TYPE));   }   catch (Exception e)   {    throw new FtpException(e);   }   for (int i = 0, n = filelist.length; i < n; i++)   {    File temp = filelist[i];    System.out.println(temp.getName());    uploadFile(temp);   }   try   {    client.changeDirectoryUp();   }   catch (Exception e)   {    throw new FtpException(e);   }  }  else  {   try   {    client.upload(file, new ALFTPTool(uploadFtpType,file.getName()));//    client.rename(file.getName(), URLEncoder.encode(file.getName(), this.CODE_TYPE));   }   catch (Exception e)   {    e.printStackTrace();    throw new FtpException(e);   }  } } public void rename(String oldname) {  try  {   String[] StrFileName = oldname.split("\.");   String newName = StrFileName[0] + FTPToolServer.EXTZIP;   client.rename(oldname, newName);  }  catch (Exception e)  {   // TODO Auto-generated catch block   e.printStackTrace();   throw new FtpException(e);  } } /*  * 删除ftp的文件夹,会删除该文件夹下所有文件夹以及文件  *   * @param filePath  / public void deleteFolder(String filePath) {  try  {   client.changeDirectory(client.currentDirectory() + "/" + filePath);   FTPFile[] ftpFileList = client.list("");   System.out.println("dir = " + client.currentDirectory());   if (ftpFileList.length == 0)   {    client.changeDirectoryUp();    client.deleteDirectory(filePath);    return;   }   for (int i = 0, n = ftpFileList.length; i < n; i++)   {    FTPFile ftpFile = ftpFileList[i];    if (ftpFile.getType() == ftpFile.TYPE_DIRECTORY)    {     deleteFolder(ftpFile.getName());    }    else if (ftpFile.getType() == ftpFile.TYPE_FILE)    {     client.deleteFile(client.currentDirectory() + "/" + ftpFile.getName());    }   }   String currentDir = client.currentDirectory();   client.changeDirectoryUp();   client.deleteDirectory(currentDir);  }  catch (Exception e)  {   throw new FtpException(e);  } } /**  * 判断是否存在  *   * @param path  * @return  / public int isExist(String path) {  path = PathToolkit.formatPath4FTP(path);  FTPFile[] list = null;  try  {   list = client.list(path);  }  catch (Exception e)  {   e.printStackTrace();   return FILE_NOT_EXITS;  }  if (list.length > 1)   return FTPFile.TYPE_DIRECTORY;  else if (list.length == 1)  {   FTPFile f = list[0];   if (f.getType() == FTPFile.TYPE_DIRECTORY)    return FTPFile.TYPE_DIRECTORY;   // 假设推理判断   String _path = path + "/" + f.getName();   try   {    int y = client.list(_path).length;    if (y == 1)     return FTPFile.TYPE_DIRECTORY;    else     return FTPFile.TYPE_FILE;   }   catch (Exception e)   {    return FTPFile.TYPE_FILE;   }  }  else  {   try   {    String tempPath = client.currentDirectory();    client.changeDirectory(path);    client.changeDirectory(tempPath);    return FTPFile.TYPE_DIRECTORY;   }   catch (Exception e)   {    return FILE_NOT_EXITS;   }  } } public void disconnect() {  if (client == null)   return;  if (client.isConnected())  {   try   {    client.disconnect(true);    return;   }   catch (Exception e)   {    try    {     client.disconnect(false);    }    catch (Exception e1)    {     e1.printStackTrace();     return;    }   }  } } static class PathToolkit {  /*   * 格式化文件路径,将其中不规范的分隔转换为标准的分隔符,并且去掉末尾的文件路径分隔符。 本方法操作系统自适应   *    * @param path   *          文件路径   * @return 格式化后的文件路径   /  public static String formatPath4File(String path)  {   String reg0 = "\\+";   String reg = "\\+|/+";   String temp = path.trim().replaceAll(reg0, "/");   temp = temp.replaceAll(reg, "/");   if (temp.length() > 1 && temp.endsWith("/"))   {    temp = temp.substring(0, temp.length() - 1);   }   temp = temp.replace('/', File.separatorChar);   return temp;  }  /*   * 格式化文件路径,将其中不规范的分隔转换为标准的分隔符 并且去掉末尾的"/"符号(适用于FTP远程文件路径或者Web资源的相对路径)。   *    * @param path   *          文件路径   * @return 格式化后的文件路径   /  public static String formatPath4FTP(String path)  {   String reg0 = "\\+";   String reg = "\\+|/+";   String temp = path.trim().replaceAll(reg0, "/");   temp = temp.replaceAll(reg, "/");   if (temp.length() > 1 && temp.endsWith("/"))   {    temp = temp.substring(0, temp.length() - 1);   }   return temp;  } } /*  * 服务器是否存在该文件夹  *   * @author ligaofeng2009-12-04  * / public boolean exists(String fileName) {  try  {   client.changeDirectory(client.currentDirectory() + "/" + fileName);   client.listNames();   return true;  }  catch (Exception e)  {   return false;  } } /*  * 是否上传到中间机器  *   * @return  * @throws Exception  */ public boolean isUpload(String cardKindCode, String cardKindFileFTPPath) throws Exception {  ALFTPTool ftpTool = new ALFTPTool();  ftpTool.setFtpPath(ftpTool.getBaseFtpPath() + cardKindFileFTPPath);    ftpTool.connect();  boolean isUpLoad = ftpTool.isExist(cardKindCode) == FTPTool.FILE_NOT_EXITS ? true : false;  ftpTool.disconnect();  return isUpLoad; } public void aborted() {  // TODO Auto-generated method stub } // ftp传送完毕触发 public void completed() { } // //传输失败时触发 public void failed() {  // TODO Auto-generated method stub } // 文件开始上传或下载时触发 public void started() {  // TODO Auto-generated method stub } // 显示已经传输的字节数 public void transferred(int arg0) {  // TODO Auto-generated method stub }}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published