ftp上传下载文件详解

1 篇文章 0 订阅

首先导入包

import org.apache.commons.NET.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

FTPClient类库主要提供了用于建立FTP连接的类。利用这些类的方法,编程人员可以远程登录到FTP服务器,列举该服务器上的目录,设置传输协议,以及传送文件。FtpClient类涵盖了几乎所有FTP的功能,FtpClient的实例变量保存了有关建立”代理”的各种信息。下面给出了这些实例变量。

public static boolean useFtpProxy

  这个变量用于表明FTP传输过程中是否使用了一个代理,因此,它实际上是一个标记,此标记若为TRUE,表明使用了一个代理主机。

  public static String ftpProxyHost

  此变量只有在变量useFtpProxy为TRUE时才有效,用于保存代理主机名。

  public static int ftpProxyPort

  此变量只有在变量useFtpProxy为TRUE时才有效,用于保存代理主机的端口地址。

FtpClient有三种不同形式的构造函数,如下所示:

  1、public FtpClient(String hostname,int port)

   此构造函数利用给出的主机名和端口号建立一条FTP连接。

  2、public FtpClient(String hostname)

  此构造函数利用给出的主机名建立一条FTP连接,使用默认端口号。

  3、FtpClient()

  此构造函数将创建一FtpClient类,但不建立FTP连接。这时,FTP连接可以用openServer方法建立。

  一旦建立了类FtpClient,就可以用这个类的方法来打开与FTP服务器的连接。类ftpClient提供了如下两个可用于打开与FTP服务器之间的连接的方法。

public void openServer(String hostname)

  这个方法用于建立一条与指定主机上的FTP服务器的连接,使用默认端口号。

  public void openServer(String host,int port)

  这个方法用于建立一条与指定主机、指定端口上的FTP服务器的连接。

  打开连接之后,接下来的工作是注册到FTP服务器。这时需要利用下面的方法。

  public void login(String username,String password)

  此方法利用参数username和password登录到FTP服务器。使用过Intemet的用户应该知道,匿名FTP服务器的登录用户名为anonymous,密码一般用自己的电子邮件地址。


下面是FtpClient类所提供的一些控制命令。

  public void cd(String remoteDirectory)

  该命令用于把远程系统上的目录切换到参数remoteDirectory所指定的目录。

  public void cdUp():该命令用于把远程系统上的目录切换到上一级目录。

  public String pwd():该命令可显示远程系统上的目录状态。

  public void binary():该命令可把传输格式设置为二进制格式。

  public void ascii():该命令可把传输协议设置为ASCII码格式。

  public void rename(String string,String string1)

  该命令可对远程系统上的目录或者文件进行重命名操作。

  除了上述方法外,类FtpClient还提供了可用于传递并检索目录清单和文件的若干方法。这些方法返回的是可供读或写的输入、输出流。下面是其中一些主要的方法。

public TelnetInputStream list()

  返回与远程机器上当前目录相对应的输入流。

  public TelnetInputStream get(String filename)

  获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。

  public TelnetOutputStream put(String filename)

  以写方式打开一输出流,通过这一输出流把文件filename传送到远程计算机。

案例:

      public FTPClient ftp = new FTPClient(); // 实例化ftp客户端对象。

      /*******************登陆***********************/

     // 开始读取 就去连接FTP服务器
    if (ftp.isConnected() == false) 
    {
     try 
     {
      ftp.connect(host_ip);// 连接 Ftp  host_ip FTP服务器ip
      try 
      {
       ftp.login(username, password);// 登陆  login ()方法登陆ftp
       ftp.setFileType(FTPClient.ASCII_FILE_TYPE);// 设置文件类型setFileType()设置ftp文件类型
      } catch (Exception e1) 
      {
       log.error(“faile to load!!!!”);
      }
     } catch (SocketException e1) 
     {
      log.error(“建立连接FTP连接失败”);
     } catch (IOException e1) 
     {
      log.error(“IO异常FTP.txt读取失败”);
     }
    }

  /**************下载文件***************************/


 public void downloadFiles()

{

      // 进入FTP服务器工作目录
      ftp.changeWorkingDirectory(ftp.printWorkingDirectory()+ remote_dir); // remote_dir FTP远程文件目录

       // 获得远程ftp目录下的文件列表
       FTPFile[] fileList = ftp.listFiles(“.”); //  . 号可替换成文件指定ftp目录。获取FTPfile文件列表。注意:文件列表包含文件夹及文件

       String[] files = ftp.listNames(); // 获取FTP服务器文件名称列表。注意:文件列表包含文件夹及文件的名称。

      /*

    fileList[0].getGroup();   // 文件所属组 ,对应有set

    fileList[0].getName();  // 文件名称, setName(“”)重命名
    fileList[0].getSize();   // 文件大小 返回long数据类型
    fileList[0].getTimestamp().getTime();   //文件最后修改时间
    fileList[0].getType(); //文件类型
    fileList[0].getUser(); //文件所属用户
    
    fileList[0].isDirectory(); // 文件是不是文件夹
    fileList[0].isFile();  //判断是不是 文件
    fileList[0].isSymbolicLink();  // ???
    fileList[0].isUnknown();  // ?、、
    fileList[0].DIRECTORY_TYPE;  //属性,文件夹类型 返回int型
    fileList[0].FILE_TYPE;  // 属性, 文件类型, 返回int型
    fileList[0].GROUP_ACCESS;  //组, 返回int型

    */

  //下载指定文件的时候,要判断指定文件的名称,比如下载,AA.TXT文件

  //遍历获取的FTP文件名称列表

    for(int i ; i < fileList.length (标注: 或者files.length ); i ++ )

   {

       //判断文件名是否包含AA.txt的。注意:在 Linux里 fileList 对象获取不到length属性。必须通过files属性获取。判断文件名称列表也必须从files数组中获取。

       if(fileList[i].getName().indexOf(“AA.txt”) != -1)

        {

           File  localfile = new File(local_dir+”/”+fileList[i].getName());

           OutPutStream ops = FileOutputStream(localFile);

           

           ftp.retrieveFile(fileList[i].getName(), ops);  //将FTP上指定文件名称的文件,下载到本地指定输出流的文件夹中。

           ops.close();

          

        }        

   }

            

}

/******************上传指定文件***********************/

/**
  * Description: 向FTP服务器上传文件
  * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保(cuihongbao@d-heaven.com)创建
  * @param url FTP服务器hostname
  * @param port FTP服务器端口
  * @param username FTP登录账号
  * @param password FTP登录密码
  * @param path FTP服务器保存目录
  * @param filename 上传到FTP服务器上的文件名
  * @param input 输入流
  * @return 成功返回true,否则返回false
  */
 public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
  boolean success = false;
  FTPClient ftp = new FTPClient();
  try {
   int reply;
   ftp.connect(url, port);//连接FTP服务器
   //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
   ftp.login(username, password);//登录
   reply = ftp.getReplyCode();
   if (!FTPReply.isPositiveCompletion(reply)) {
    ftp.disconnect();
    return success;
   }
   ftp.changeWorkingDirectory(path);
   ftp.storeFile(filename, input);   
   
   input.close();
   ftp.logout();
   success = true;
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (ftp.isConnected()) {
    try {
     ftp.disconnect();
    } catch (IOException ioe) {
    }
   }
  }
  return success;
 }

@Test
 public void testUpLoadFromDisk(){
  try {
   FileInputStream in=new FileInputStream(new File(“D:/test.txt”));
   boolean flag = uploadFile(“127.0.0.1”, 21, “test”, “test”, “D:/ftp”, “test.txt”, in);
   System.out.println(flag);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }

 案例一:

 用apache FTP client实现FTP客户端–支持断点续传和中文文件

利用org.apache.commons.Net.ftp包实现一个简单的ftp客户端实用类。主要实现一下功能

1.支持上传下载。支持断点续传

2.支持进度汇报

3.支持对于中文目录及中文文件创建的支持。 

枚举类UploadStatus代码

 

[java]  view plain copy
  1.  1public enum UploadStatus {       
  2.  2.     Create_Directory_Fail,      //远程服务器相应目录创建失败       
  3.  3.     Create_Directory_Success,   //远程服务器闯将目录成功       
  4.  4.     Upload_New_File_Success,    //上传新文件成功       
  5.  5.     Upload_New_File_Failed,     //上传新文件失败       
  6.  6.     File_Exits,                 //文件已经存在       
  7.  7.     Remote_Bigger_Local,        //远程文件大于本地文件       
  8.  8.     Upload_From_Break_Success,  //断点续传成功       
  9.  9.     Upload_From_Break_Failed,   //断点续传失败       
  10. 10.     Delete_Remote_Faild;        //删除远程文件失败       
  11. 11. }    

 

 

枚举类DownloadStatus代码

 

[c-sharp]  view plain copy
  1. 1. public enum DownloadStatus {       
  2. 2.     Remote_File_Noexist,    //远程文件不存在       
  3. 3.     Local_Bigger_Remote,    //本地文件大于远程文件       
  4. 4.     Download_From_Break_Success,    //断点下载文件成功       
  5. 5.     Download_From_Break_Failed,     //断点下载文件失败       
  6. 6.     Download_New_Success,           //全新下载文件成功       
  7. 7.     Download_New_Failed;            //全新下载文件失败       
  8. 8. }    

 

 

 

 

核心FTP代码

 

[c-sharp]  view plain copy
  1. 核心FTP代码  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.io.PrintWriter;  
  9. import java.io.RandomAccessFile;  
  10.   
  11. import open.mis.data.DownloadStatus;  
  12. import open.mis.data.UploadStatus;  
  13.   
  14. import org.apache.commons.net.PrintCommandListener;  
  15. import org.apache.commons.net.ftp.FTP;  
  16. import org.apache.commons.net.ftp.FTPClient;  
  17. import org.apache.commons.net.ftp.FTPFile;  
  18. import org.apache.commons.net.ftp.FTPReply;  
  19.   
  20. /** 
  21. * 支持断点续传的FTP实用类 
  22. * @author BenZhou 
  23. * @version 0.1 实现基本断点上传下载 
  24. * @version 0.2 实现上传下载进度汇报 
  25. * @version 0.3 实现中文目录创建及中文文件创建,添加对于中文的支持 
  26. */  
  27. public class ContinueFTP {  
  28. public FTPClient ftpClient = new FTPClient();  
  29.   
  30. public ContinueFTP(){  
  31.    //设置将过程中使用到的命令输出到控制台  
  32.    this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));  
  33. }  
  34.   
  35. /** 
  36. * 连接到FTP服务器 
  37. * @param hostname 主机名 
  38. * @param port 端口 
  39. * @param username 用户名 
  40. * @param password 密码 
  41. * @return 是否连接成功 
  42. * @throws IOException 
  43. */  
  44. public boolean connect(String hostname,int port,String username,String password) throws IOException{  
  45.    ftpClient.connect(hostname, port);  
  46.    ftpClient.setControlEncoding(”GBK”);  
  47.    if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){  
  48.     if(ftpClient.login(username, password)){  
  49.      return true;  
  50.     }  
  51.    }  
  52.    disconnect();  
  53.    return false;  
  54. }  
  55.   
  56. /** 
  57. * 从FTP服务器上下载文件,支持断点续传,上传百分比汇报 
  58. * @param remote 远程文件路径 
  59. * @param local 本地文件路径 
  60. * @return 上传的状态 
  61. * @throws IOException 
  62. */  
  63. public DownloadStatus download(String remote,String local) throws IOException{  
  64.    //设置被动模式  
  65.    ftpClient.enterLocalPassiveMode();  
  66.    //设置以二进制方式传输  
  67.    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  68.    DownloadStatus result;  
  69.     
  70.    //检查远程文件是否存在  
  71.    FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes(“GBK”),“iso-8859-1”));  
  72.    if(files.length != 1){  
  73.     System.out.println(“远程文件不存在”);  
  74.     return DownloadStatus.Remote_File_Noexist;  
  75.    }  
  76.     
  77.    long lRemoteSize = files[0].getSize();  
  78.    File f = new File(local);  
  79.    //本地存在文件,进行断点下载  
  80.    if(f.exists()){  
  81.     long localSize = f.length();  
  82.     //判断本地文件大小是否大于远程文件大小  
  83.     if(localSize >= lRemoteSize){  
  84.      System.out.println(“本地文件大于远程文件,下载中止”);  
  85.      return DownloadStatus.Local_Bigger_Remote;  
  86.     }  
  87.      
  88.     //进行断点续传,并记录状态  
  89.     FileOutputStream out = new FileOutputStream(f,true);  
  90.     ftpClient.setRestartOffset(localSize);  
  91.     InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes(“GBK”),“iso-8859-1”));  
  92.     byte[] bytes = new byte[1024];  
  93.     long step = lRemoteSize /100;  
  94.     long process=localSize /step;  
  95.     int c;  
  96.     while((c = in.read(bytes))!= -1){  
  97.      out.write(bytes,0,c);  
  98.      localSize+=c;  
  99.      long nowProcess = localSize /step;  
  100.      if(nowProcess > process){  
  101.       process = nowProcess;  
  102.       if(process % 10 == 0)  
  103.        System.out.println(“下载进度:”+process);  
  104.       //TODO 更新文件下载进度,值存放在process变量中  
  105.      }  
  106.     }  
  107.     in.close();  
  108.     out.close();  
  109.     boolean isDo = ftpClient.completePendingCommand();  
  110.     if(isDo){  
  111.      result = DownloadStatus.Download_From_Break_Success;  
  112.     }else {  
  113.      result = DownloadStatus.Download_From_Break_Failed;  
  114.     }  
  115.    }else {  
  116.     OutputStream out = new FileOutputStream(f);  
  117.     InputStream in= ftpClient.retrieveFileStream(new String(remote.getBytes(“GBK”),“iso-8859-1”));  
  118.     byte[] bytes = new byte[1024];  
  119.     long step = lRemoteSize /100;  
  120.     long process=0;  
  121.     long localSize = 0L;  
  122.     int c;  
  123.     while((c = in.read(bytes))!= -1){  
  124.      out.write(bytes, 0, c);  
  125.      localSize+=c;  
  126.      long nowProcess = localSize /step;  
  127.      if(nowProcess > process){  
  128.       process = nowProcess;  
  129.       if(process % 10 == 0)  
  130.        System.out.println(“下载进度:”+process);  
  131.       //TODO 更新文件下载进度,值存放在process变量中  
  132.      }  
  133.     }  
  134.     in.close();  
  135.     out.close();  
  136.     boolean upNewStatus = ftpClient.completePendingCommand();  
  137.     if(upNewStatus){  
  138.      result = DownloadStatus.Download_New_Success;  
  139.     }else {  
  140.      result = DownloadStatus.Download_New_Failed;  
  141.     }  
  142.    }  
  143.    return result;  
  144. }  
  145.   
  146. /** 
  147. * 上传文件到FTP服务器,支持断点续传 
  148. * @param local 本地文件名称,绝对路径 
  149. * @param remote 远程文件路径,使用/home/directory1/subdirectory/file.ext 按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构 
  150. * @return 上传结果 
  151. * @throws IOException 
  152. */  
  153. public UploadStatus upload(String local,String remote) throws IOException{  
  154.    //设置PassiveMode传输  
  155.    ftpClient.enterLocalPassiveMode();  
  156.    //设置以二进制流的方式传输  
  157.    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  158.    ftpClient.setControlEncoding(”GBK”);  
  159.    UploadStatus result;  
  160.    //对远程目录的处理  
  161.    String remoteFileName = remote;  
  162.    if(remote.contains(“/”)){  
  163.     remoteFileName = remote.substring(remote.lastIndexOf(”/”)+1);  
  164.     //创建服务器远程目录结构,创建失败直接返回  
  165.     if(CreateDirecroty(remote, ftpClient)==UploadStatus.Create_Directory_Fail){  
  166.      return UploadStatus.Create_Directory_Fail;  
  167.     }  
  168.    }  
  169.     
  170.    //检查远程是否存在文件  
  171.    FTPFile[] files = ftpClient.listFiles(new String(remoteFileName.getBytes(“GBK”),“iso-8859-1”));  
  172.    if(files.length == 1){  
  173.     long remoteSize = files[0].getSize();  
  174.     File f = new File(local);  
  175.     long localSize = f.length();  
  176.     if(remoteSize==localSize){  
  177.      return UploadStatus.File_Exits;  
  178.     }else if(remoteSize > localSize){  
  179.      return UploadStatus.Remote_Bigger_Local;  
  180.     }  
  181.      
  182.     //尝试移动文件内读取指针,实现断点续传  
  183.     result = uploadFile(remoteFileName, f, ftpClient, remoteSize);  
  184.      
  185.     //如果断点续传没有成功,则删除服务器上文件,重新上传  
  186.     if(result == UploadStatus.Upload_From_Break_Failed){  
  187.      if(!ftpClient.deleteFile(remoteFileName)){  
  188.       return UploadStatus.Delete_Remote_Faild;  
  189.      }  
  190.      result = uploadFile(remoteFileName, f, ftpClient, 0);  
  191.     }  
  192.    }else {  
  193.     result = uploadFile(remoteFileName, new File(local), ftpClient, 0);  
  194.    }  
  195.    return result;  
  196. }  
  197. /** 
  198. * 断开与远程服务器的连接 
  199. * @throws IOException 
  200. */  
  201. public void disconnect() throws IOException{  
  202.    if(ftpClient.isConnected()){  
  203.     ftpClient.disconnect();  
  204.    }  
  205. }  
  206.   
  207. /** 
  208. * 递归创建远程服务器目录 
  209. * @param remote 远程服务器文件绝对路径 
  210. * @param ftpClient FTPClient对象 
  211. * @return 目录创建是否成功 
  212. * @throws IOException 
  213. */  
  214. public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{  
  215.    UploadStatus status = UploadStatus.Create_Directory_Success;  
  216.    String directory = remote.substring(0,remote.lastIndexOf(”/”)+1);  
  217.    if(!directory.equalsIgnoreCase(“/”)&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes(“GBK”),“iso-8859-1”))){  
  218.     //如果远程目录不存在,则递归创建远程服务器目录  
  219.     int start=0;  
  220.     int end = 0;  
  221.     if(directory.startsWith(“/”)){  
  222.      start = 1;  
  223.     }else{  
  224.      start = 0;  
  225.     }  
  226.     end = directory.indexOf(”/”,start);  
  227.     while(true){  
  228.      String subDirectory = new String(remote.substring(start,end).getBytes(“GBK”),“iso-8859-1”);  
  229.      if(!ftpClient.changeWorkingDirectory(subDirectory)){  
  230.       if(ftpClient.makeDirectory(subDirectory)){  
  231.        ftpClient.changeWorkingDirectory(subDirectory);  
  232.       }else {  
  233.        System.out.println(“创建目录失败”);  
  234.        return UploadStatus.Create_Directory_Fail;  
  235.       }  
  236.      }  
  237.       
  238.      start = end + 1;  
  239.      end = directory.indexOf(”/”,start);  
  240.       
  241.      //检查所有目录是否创建完毕  
  242.      if(end <= start){  
  243.       break;  
  244.      }  
  245.     }  
  246.    }  
  247.    return status;  
  248. }  
  249.   
  250. /** 
  251. * 上传文件到服务器,新上传和断点续传 
  252. * @param remoteFile 远程文件名,在上传之前已经将服务器工作目录做了改变 
  253. * @param localFile 本地文件File句柄,绝对路径 
  254. * @param processStep 需要显示的处理进度步进值 
  255. * @param ftpClient FTPClient引用 
  256. * @return 
  257. * @throws IOException 
  258. */  
  259. public UploadStatus uploadFile(String remoteFile,File localFile,FTPClient ftpClient,long remoteSize) throws IOException{  
  260.    UploadStatus status;  
  261.    //显示进度的上传  
  262.    long step = localFile.length() / 100;  
  263.    long process = 0;  
  264.    long localreadbytes = 0L;  
  265.    RandomAccessFile raf = new RandomAccessFile(localFile,“r”);  
  266.    OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes(“GBK”),“iso-8859-1”));  
  267.    //断点续传  
  268.    if(remoteSize>0){  
  269.     ftpClient.setRestartOffset(remoteSize);  
  270.     process = remoteSize /step;  
  271.     raf.seek(remoteSize);  
  272.     localreadbytes = remoteSize;  
  273.    }  
  274.    byte[] bytes = new byte[1024];  
  275.    int c;  
  276.    while((c = raf.read(bytes))!= -1){  
  277.     out.write(bytes,0,c);  
  278.     localreadbytes+=c;  
  279.     if(localreadbytes / step != process){  
  280.      process = localreadbytes / step;  
  281.      System.out.println(“上传进度:” + process);  
  282.      //TODO 汇报上传状态  
  283.     }  
  284.    }  
  285.    out.flush();  
  286.    raf.close();  
  287.    out.close();  
  288.    boolean result =ftpClient.completePendingCommand();  
  289.    if(remoteSize > 0){  
  290.     status = result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;  
  291.    }else {  
  292.     status = result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;  
  293.    }  
  294.    return status;  
  295. }  
  296.   
  297. public static void main(String[] args) {  
  298.    ContinueFTP myFtp = new ContinueFTP();  
  299.    try {  
  300.     myFtp.connect(”192.168.21.181”, 21, “nid”“123”);  
  301. //    myFtp.ftpClient.makeDirectory(new String(“电视剧”.getBytes(“GBK”),”iso-8859-1”));  
  302. //    myFtp.ftpClient.changeWorkingDirectory(new String(“电视剧”.getBytes(“GBK”),”iso-8859-1”));  
  303. //    myFtp.ftpClient.makeDirectory(new String(“走西口”.getBytes(“GBK”),”iso-8859-1”));  
  304. //    System.out.println(myFtp.upload(“E://yw.flv”, ”/yw.flv”,5));  
  305. //    System.out.println(myFtp.upload(“E://走西口24.mp4”,”/央视走西口/新浪网/走西口24.mp4”));  
  306.     System.out.println(myFtp.download(“/央视走西口/新浪网/走西口24.mp4”“E://走西口242.mp4”));  
  307.     myFtp.disconnect();  
  308.    } catch (IOException e) {  
  309.     System.out.println(“连接FTP出错:”+e.getMessage());  
  310.    }  
  311. }  
  312. }  



案例二:

ftp 用法:

FTP客户端

package cm;
import Java.io.File;

import java.io.IOException;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpHelper {
  private FTPClient ftpClient = new FTPClient();

  /**
      * 连接到FTP服务器
      *
      * @param hostname
      *            主机名
      * @param port
      *            端口
      * @param username
      *            用户名
      * @param password
      *            密码
      * @return 是否连接成功
      * @throws IOException
      */
     public boolean connect(String hostname, int port, String username,
             String password) throws IOException {
         ftpClient.connect(hostname, port);
         ftpClient.setControlEncoding(“GBK”);
         if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
             if (ftpClient.login(username, password)) {
                 return true;
             }
         }
         disconnect();
         return false;
     }

     /**
      * 从FTP服务器上下载文件,支持断点续传,上传百分比汇报
      *
      * @param remote
      *            远程文件路径
      * @param local
      *            本地文件路径
      * @return 上传的状态
      * @throws IOException
      */
     public DownloadStatus download(String remote, String local)
             throws IOException {
         // 设置被动模式
         ftpClient.enterLocalPassiveMode();
         // 设置以二进制方式传输
         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
         DownloadStatus result;

         // 检查远程文件是否存在
         FTPFile[] files = ftpClient.listFiles(new String(
                 remote.getBytes(“GBK”), “iso-8859-1”));
         if (files.length != 1) {
             System.out.println(“远程文件不存在”);
             return DownloadStatus.Remote_File_Noexist;
         }

         long lRemoteSize = files[0].getSize();
         File f = new File(local);
         // 本地存在文件,进行断点下载
         if (f.exists()) {
             long localSize = f.length();
             // 判断本地文件大小是否大于远程文件大小
             if (localSize >= lRemoteSize) {
                 System.out.println(“本地文件大于远程文件,下载中止”);
                 return DownloadStatus.Local_Bigger_Remote;
             }

             // 进行断点续传,并记录状态
             FileOutputStream out = new FileOutputStream(f, true);
             ftpClient.setRestartOffset(localSize);
             InputStream in = ftpClient.retrieveFileStream(new String(remote
                     .getBytes(“GBK”), “iso-8859-1”));
             byte[] bytes = new byte[1024];
             long step = lRemoteSize / 100;
             long process = localSize / step;
             int c;
             while ((c = in.read(bytes)) != -1) {
                 out.write(bytes, 0, c);
                 localSize += c;
                 long nowProcess = localSize / step;
                 if (nowProcess > process) {
                     process = nowProcess;
                     if (process % 10 == 0)
                         System.out.println(“下载进度:” + process);
                     // TODO 更新文件下载进度,值存放在process变量中
                 }
             }
             in.close();
             out.close();
             boolean isDo = ftpClient.completePendingCommand();
             if (isDo) {
                 result = DownloadStatus.Download_From_Break_Success;
             } else {
                 result = DownloadStatus.Download_From_Break_Failed;
             }
         } else {
             OutputStream out = new FileOutputStream(f);
             InputStream in = ftpClient.retrieveFileStream(new String(remote
                     .getBytes(“GBK”), “iso-8859-1”));
             byte[] bytes = new byte[1024];
             long step = lRemoteSize / 100;
             long process = 0;
             long localSize = 0L;
             int c;
             while ((c = in.read(bytes)) != -1) {
                 out.write(bytes, 0, c);
                 localSize += c;
                 long nowProcess = localSize / step;
                 if (nowProcess > process) {
                     process = nowProcess;
                     if (process % 10 == 0)
                         System.out.println(“下载进度:” + process);
                     // TODO 更新文件下载进度,值存放在process变量中
                 }
             }
             in.close();
             out.close();
             boolean upNewStatus = ftpClient.completePendingCommand();
             if (upNewStatus) {
                 result = DownloadStatus.Download_New_Success;
             } else {
                 result = DownloadStatus.Download_New_Failed;
             }
         }
         return result;
     }

     /**
      * 上传文件到FTP服务器,支持断点续传
      *
      * @param local
      *            本地文件名称,绝对路径
      * @param remote
      *            远程文件路径,使用/home/directory1/subdirectory/file.ext
      *            按照linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构
      * @return 上传结果
      * @throws IOException
      */
     public UploadStatus upload(String local, String remote) throws IOException {
         // 设置PassiveMode传输
         ftpClient.enterLocalPassiveMode();
         // 设置以二进制流的方式传输
         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
         ftpClient.setControlEncoding(“GBK”);
         UploadStatus result;
         // 对远程目录的处理
         String remoteFileName = remote;
         if (remote.contains(“/”)) {
             remoteFileName = remote.substring(remote.lastIndexOf(“/”) + 1);
             // 创建服务器远程目录结构,创建失败直接返回
             if (createDirecroty(remote, ftpClient) == UploadStatus.Create_Directory_Fail) {
                 return UploadStatus.Create_Directory_Fail;
             }
         }
         //ftpClient.feat();

 //      System.out.println( ftpClient.getReply());
 //      System.out.println( ftpClient.acct(null));
 //      System.out.println(ftpClient.getReplyCode());
 //      System.out.println(ftpClient.getReplyString());


         // 检查远程是否存在文件
         FTPFile[] files = ftpClient.listFiles(new String(remoteFileName
                 .getBytes(“GBK”), “iso-8859-1”));
         if (files.length == 1) {
             long remoteSize = files[0].getSize();
             File f = new File(local);
             long localSize = f.length();
             if (remoteSize == localSize) { // 文件存在
                 return UploadStatus.File_Exits;
             } else if (remoteSize > localSize) {
                 return UploadStatus.Remote_Bigger_Local;
             }

             // 尝试移动文件内读取指针,实现断点续传
             result = uploadFile(remoteFileName, f, ftpClient, remoteSize);

             // 如果断点续传没有成功,则删除服务器上文件,重新上传
             if (result == UploadStatus.Upload_From_Break_Failed) {
                 if (!ftpClient.deleteFile(remoteFileName)) {
                     return UploadStatus.Delete_Remote_Faild;
                 }
                 result = uploadFile(remoteFileName, f, ftpClient, 0);
             }
         } else {
             result = uploadFile(remoteFileName, new File(local), ftpClient, 0);
         }
         return result;
     }

     /**
      * 断开与远程服务器的连接
      *
      * @throws IOException
      */
     public void disconnect() throws IOException {
         if (ftpClient.isConnected()) {
             ftpClient.disconnect();
         }
     }

     /**
      * 递归创建远程服务器目录
      *
      * @param remote
      *            远程服务器文件绝对路径
      * @param ftpClient
      *            FTPClient对象
      * @return 目录创建是否成功
      * @throws IOException
      */
     public UploadStatus createDirecroty(String remote, FTPClient ftpClient)
             throws IOException {
         UploadStatus status = UploadStatus.Create_Directory_Success;
         String directory = remote.substring(0, remote.lastIndexOf(“/”) + 1);
         if (!directory.equalsIgnoreCase(“/”)
                 && !ftpClient.changeWorkingDirectory(new String(directory
                         .getBytes(“GBK”), “iso-8859-1”))) {
             // 如果远程目录不存在,则递归创建远程服务器目录
             int start = 0;
             int end = 0;
             if (directory.startsWith(“/”)) {
                 start = 1;
             } else {
                 start = 0;
             }
             end = directory.indexOf(“/”, start);
             while (true) {
                 String subDirectory = new String(remote.substring(start, end)
                         .getBytes(“GBK”), “iso-8859-1”);
                 if (!ftpClient.changeWorkingDirectory(subDirectory)) {
                     if (ftpClient.makeDirectory(subDirectory)) {
                         ftpClient.changeWorkingDirectory(subDirectory);
                     } else {
                         System.out.println(“创建目录失败”);
                         return UploadStatus.Create_Directory_Fail;
                     }
                 }

                 start = end + 1;
                 end = directory.indexOf(“/”, start);

                 // 检查所有目录是否创建完毕
                 if (end <= start) {
                     break;
                 }
             }
         }
         return status;
     }

     /**
      * 上传文件到服务器,新上传和断点续传
      *
      * @param remoteFile
      *            远程文件名,在上传之前已经将服务器工作目录做了改变
      * @param localFile
      *            本地文件File句柄,绝对路径
      * @param processStep
      *            需要显示的处理进度步进值
      * @param ftpClient
      *            FTPClient引用
      * @return
      * @throws IOException
      */
     public UploadStatus uploadFile(String remoteFile, File localFile,
             FTPClient ftpClient, long remoteSize) throws IOException {
         UploadStatus status;
         // 显示进度的上传
         long step = localFile.length() / 100;
         long process = 0;
         long localreadbytes = 0L;
         RandomAccessFile raf = new RandomAccessFile(localFile, “r”);
         String remote = new String(remoteFile.getBytes(“GBK”), “iso-8859-1”);
         OutputStream out = ftpClient.appendFileStream(remote);
         if(out==null)
         {
             String message = ftpClient.getReplyString();
             throw new RuntimeException(message);
         }
         // 断点续传
         if (remoteSize > 0) {
             ftpClient.setRestartOffset(remoteSize);
             process = remoteSize / step;
             raf.seek(remoteSize);
             localreadbytes = remoteSize;
         }
         byte[] bytes = new byte[1024];
         int c;
         while ((c = raf.read(bytes)) != -1) {
             out.write(bytes, 0, c);
             localreadbytes += c;
             if (localreadbytes / step != process) {
                 process = localreadbytes / step;
                 System.out.println(“上传进度:” + process);
                 // TODO 汇报上传状态

             }
         }
         out.flush();
         raf.close();
         out.close();
         boolean result = ftpClient.completePendingCommand();
         if (remoteSize > 0) {
             status = result ? UploadStatus.Upload_From_Break_Success
                     : UploadStatus.Upload_From_Break_Failed;
         } else {
             status = result ? UploadStatus.Upload_New_File_Success
                     : UploadStatus.Upload_New_File_Failed;
         }
         return status;
     }

     /**
      * 获取指定目录下的文件名称列表
      * @author HQQW510_64
      * @param currentDir 需要获取其子目录的当前目录名称
      * @return 返回子目录字符串数组
      */
     public String[] GetFileNames(String currentDir) {
         String[] dirs = null;
         try {
             if(currentDir==null)
             dirs = ftpClient.listNames();
             else
                 dirs = ftpClient.listNames(currentDir);
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         return dirs;
     }

     /**
      * 获取指定目录下的文件与目录信息集合
      * @param currentDir 指定的当前目录
      * @return 返回的文件集合
      */
     public FTPFile[] GetDirAndFilesInfo(String currentDir)
     {
         FTPFile[] files=null;

         try
         {
             if(currentDir==null)
                 files=ftpClient.listFiles();
             else
              files = ftpClient.listFiles(currentDir);
      }
      catch(IOException ex)
      {
          // TODO Auto-generated catch block
          ex.printStackTrace();
      }
      return files;
 }
}



案例三 

JAVA中使用FTPClient上传下载

        在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件、下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件。

一、上传文件

         原理就不介绍了,大家直接看代码吧

[Java]  view plain copy
  1. /** 
  2.  * Description: 向FTP服务器上传文件 
  3.  * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保(cuihongbao@d-heaven.com)创建 
  4.  * @param url FTP服务器hostname 
  5.  * @param port FTP服务器端口 
  6.  * @param username FTP登录账号 
  7.  * @param password FTP登录密码 
  8.  * @param path FTP服务器保存目录 
  9.  * @param filename 上传到FTP服务器上的文件名 
  10.  * @param input 输入流 
  11.  * @return 成功返回true,否则返回false 
  12.  */  
  13. public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {  
  14.     boolean success = false;  
  15.     FTPClient ftp = new FTPClient();  
  16.     try {  
  17.         int reply;  
  18.         ftp.connect(url, port);//连接FTP服务器  
  19.         //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
  20.         ftp.login(username, password);//登录  
  21.         reply = ftp.getReplyCode();  
  22.         if (!FTPReply.isPositiveCompletion(reply)) {  
  23.             ftp.disconnect();  
  24.             return success;  
  25.         }  
  26.         ftp.changeWorkingDirectory(path);  
  27.         ftp.storeFile(filename, input);           
  28.           
  29.         input.close();  
  30.         ftp.logout();  
  31.         success = true;  
  32.     } catch (IOException e) {  
  33.         e.printStackTrace();  
  34.     } finally {  
  35.         if (ftp.isConnected()) {  
  36.             try {  
  37.                 ftp.disconnect();  
  38.             } catch (IOException ioe) {  
  39.             }  
  40.         }  
  41.     }  
  42.     return success;  
  43. }<pre></pre>  

 

下面我们写两个小例子:

1.将本地文件上传到FTP服务器上,代码如下:

[Java]  view plain copy
  1. @Test  
  2. public void testUpLoadFromDisk(){  
  3.     try {  
  4.         FileInputStream in=new FileInputStream(new File(“D:/test.txt”));  
  5.         boolean flag = uploadFile(“127.0.0.1”21“test”“test”“D:/ftp”“test.txt”, in);  
  6.         System.out.println(flag);  
  7.     } catch (FileNotFoundException e) {  
  8.         e.printStackTrace();  
  9.     }  
  10. }<pre></pre>  

2.在FTP服务器上生成一个文件,并将一个字符串写入到该文件中

[Java]  view plain copy
  1. @Test  
  2. public void testUpLoadFromString(){  
  3.     try {  
  4.         InputStream input = new ByteArrayInputStream(“test ftp”.getBytes(“utf-8”));  
  5.         boolean flag = uploadFile(“127.0.0.1”21“test”“test”“D:/ftp”“test.txt”, input);  
  6.         System.out.println(flag);  
  7.     } catch (UnsupportedEncodingException e) {  
  8.         e.printStackTrace();  
  9.     }  
  10. }<pre></pre>  


二、下载文件

       从FTP服务器下载文件的代码也很简单,参考如下:

[Java]  view plain copy
  1. /** 
  2.  * Description: 从FTP服务器下载文件 
  3.  * @Version1.0 Jul 27, 2008 5:32:36 PM by 崔红保(cuihongbao@d-heaven.com)创建 
  4.  * @param url FTP服务器hostname 
  5.  * @param port FTP服务器端口 
  6.  * @param username FTP登录账号 
  7.  * @param password FTP登录密码 
  8.  * @param remotePath FTP服务器上的相对路径 
  9.  * @param fileName 要下载的文件名 
  10.  * @param localPath 下载后保存到本地的路径 
  11.  * @return 
  12.  */  
  13. public static boolean downFile(String url, int port,String username, String password, String remotePath,String fileName,String localPath) {  
  14.     boolean success = false;  
  15.     FTPClient ftp = new FTPClient();  
  16.     try {  
  17.         int reply;  
  18.         ftp.connect(url, port);  
  19.         //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
  20.         ftp.login(username, password);//登录  
  21.         reply = ftp.getReplyCode();  
  22.         if (!FTPReply.isPositiveCompletion(reply)) {  
  23.             ftp.disconnect();  
  24.             return success;  
  25.         }  
  26.         ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录  
  27.         FTPFile[] fs = ftp.listFiles();  
  28.         for(FTPFile ff:fs){  
  29.             if(ff.getName().equals(fileName)){  
  30.                 File localFile = new File(localPath+“/”+ff.getName());  
  31.                   
  32.                 OutputStream is = new FileOutputStream(localFile);   
  33.                 ftp.retrieveFile(ff.getName(), is);  
  34.                 is.close();  
  35.             }  
  36.         }  
  37.           
  38.         ftp.logout();  
  39.         success = true;  
  40.     } catch (IOException e) {  
  41.         e.printStackTrace();  
  42.     } finally {  
  43.         if (ftp.isConnected()) {  
  44.             try {  
  45.                 ftp.disconnect();  
  46.             } catch (IOException ioe) {  
  47.             }  
  48.         }  
  49.     }  
  50.     return success;  
  51. }<pre></pre>  



案例三:

  1. /** 
  2.  * 支持断点续传的FTP实用类  
  3.  *  
  4.  * @author chenxin 
  5.  * @version [版本号, 2012-5-21] 
  6.  * @see [相关类/方法] 
  7.  * @since [产品/模块版本] 
  8.  */  
  9. public class FtpUtils  {  
  10.   
  11.     private FTPClient ftpClient = null;  
  12.    private static final Logger logger = Logger.getLogger(FtpUtils.class);  
  13.    private String hostname;  
  14.    private String username;  
  15.    private String password;  
  16.    private int port;  
  17.    private static final String EPUB_DIR = “epub_file”;  
  18.      
  19.    public FtpUtils()  
  20.    {  
  21.        ftpClient = new FTPClient();  
  22.        username = ServerConfig.get(”ftp/ftp-user”“”);  
  23.        password = ServerConfig.get(”ftp/ftp-password”“”);  
  24.        hostname = ServerConfig.get(”ftp/ftp-host”“”);  
  25.        port = ServerConfig.getInt(”ftp/ftp-port”21);  
  26. //       {     
  27. //           //设置将过程中使用到的命令输出到控制台     
  28. //           ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));     
  29. //       }   
  30.    }    
  31.         
  32.    /**   
  33.     * 连接到FTP服务器  
  34.     * @param hostname 主机名  
  35.     * @param port 端口  
  36.     * @param username 用户名  
  37.     * @param password 密码  
  38.     * @return 是否连接成功  
  39.     * @throws IOException  
  40.     */    
  41.    public boolean connect() throws IOException{    
  42.        ftpClient.connect(hostname, port);     
  43.        ftpClient.setControlEncoding(ServerConfig.get(”ftp/ftp-charset”“GBK”));     
  44.        if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){     
  45.            if(ftpClient.login(username, password)){    
  46.                // 设置被动模式  
  47.                ftpClient.enterLocalPassiveMode();  
  48.                // 设置以二进制方式传输  
  49.                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  50.                return true;     
  51.            }     
  52.        }     
  53.        disconnect();     
  54.        return false;     
  55.    }     
  56.      
  57.    public boolean reconnect() throws IOException  
  58.    {    
  59.          disconnect();    
  60.          ftpClient.connect(hostname, port);     
  61.          ftpClient.setControlEncoding(ServerConfig.get(”ftp/ftp-charset”“GBK”));     
  62.          if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){     
  63.              if(ftpClient.login(username, password)){    
  64.                  // 设置被动模式  
  65.                  ftpClient.enterLocalPassiveMode();  
  66.                  // 设置以二进制方式传输  
  67.                  ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  68.                  return true;     
  69.              }     
  70.          }     
  71.          disconnect();     
  72.          return false;     
  73.  }     
  74.         
  75.  /** 
  76.   * 从FTP服务器上下载文件,上传百分比 
  77.   * @param remote 
  78.   * @param dir 
  79.   * @param fileName 
  80.   * @return 
  81.   * @throws IOException 
  82.   * @see [类、类#方法、类#成员] 
  83.   */  
  84.     public boolean download(String remote, String dir, String fileName)  
  85.         throws IOException  
  86.     {  
  87.         File file = new File(dir + File.separator + fileName);  
  88.         // 本地存在文件  
  89.         if (file.exists())  
  90.         {  
  91.             if (logger.isDebugEnabled())  
  92.             {  
  93.                 logger.debug(”File is existsed.”);  
  94.             }  
  95.             // 如果文件存在,但还未从FTP服务器上完全取下来,则需要等待  
  96.             Long initialSize = 0L;  
  97.             int i = 0;  
  98.             while (initialSize != file.length())  
  99.             {  
  100.                 i++;  
  101.                 initialSize = file.length();  
  102.                 try  
  103.                 {  
  104.                     Thread.sleep(100L);  
  105.                 }  
  106.                 catch (InterruptedException e)  
  107.                 {  
  108.                     e.printStackTrace();  
  109.                 }  
  110.             }  
  111.               
  112.             if (i > 1)  
  113.             {  
  114.                 // 如果是刚下完的文件,则不需要再比对大小是否一致  
  115.                 return true;  
  116.             }  
  117.         }  
  118.           
  119.         Long localSize = file.length();  
  120.         File localDir = new File(dir);  
  121.         if (!localDir.exists())  
  122.         {  
  123.             localDir.mkdirs();  
  124.         }  
  125.           
  126.         // 检查远程文件是否存在  
  127.         if (remote.startsWith(“/”))  
  128.         {  
  129.             remote = remote.substring(1);  
  130.         }  
  131.           
  132.         if (ftpClient.listNames(remote).length <= 0)  
  133.         {     
  134.             // 文件不存在  
  135.             logger.error(”Could not find file from ftp server: ” + remote);  
  136.             return false;  
  137.         }  
  138.           
  139.         // 计算远程文件大小  
  140.         String s = ”SIZE ” + remote + “\r\n”;  
  141.         ftpClient.sendCommand(s);  
  142.         String s1 = ftpClient.getReplyString();  
  143.         Long remoteSize = Long.parseLong(s1.substring(3).trim());  
  144.         if (logger.isDebugEnabled())  
  145.         {  
  146.             logger.debug(”localsize: ” + localSize + “, remoteSize: ” + remoteSize);  
  147.         }  
  148.         if (remoteSize.equals(localSize))  
  149.         {  
  150.             if (logger.isDebugEnabled())  
  151.             {  
  152.                 logger.debug(”File’s size not changed.”);  
  153.             }  
  154.             return true;  
  155.         }  
  156.         else if (localSize != 0L)  
  157.         {  
  158.             if (logger.isDebugEnabled())  
  159.             {  
  160.                 logger.debug(”File’s size changed which needed re-download.”);  
  161.             }  
  162.             //远程文件和本地文件大小不一致,则删除本地文件  
  163.             file.delete();  
  164.             //如果是EPUB书路径,则需要把解压过的临时文件也一并删除  
  165.             if (dir.indexOf(EPUB_DIR) > 0)  
  166.             {  
  167.                 deleteAll(localDir);  
  168.             }  
  169.         }  
  170.           
  171.         // 重连以回到根目录  
  172.         reconnect();  
  173.         OutputStream out = new FileOutputStream(file);  
  174.         InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes(“UTF-8”),  
  175.             ServerConfig.get(”ftp/ftp-charset”“GBK”)));  
  176.         if (logger.isDebugEnabled())  
  177.         {  
  178.             logger.debug(”Begin to downloaded file from ftp.”);  
  179.         }  
  180.         byte[] bytes = new byte[1024];  
  181.         int count;  
  182.         while ((count = in.read(bytes)) != -1)  
  183.         {  
  184.             out.write(bytes, 0, count);  
  185.         }  
  186.         if (logger.isDebugEnabled())  
  187.         {  
  188.             logger.debug(”File has been downloaded from ftp successfully.”);  
  189.         }  
  190.         in.close();  
  191.         out.close();  
  192.         boolean upNewStatus = ftpClient.completePendingCommand();  
  193.         if (upNewStatus)  
  194.         {  
  195.             return true;  
  196.         }  
  197.         else  
  198.         {  
  199.             return false;  
  200.         }  
  201.     }  
  202.       
  203.     //递归删除文件夹  
  204.     private void deleteAll(File file)  
  205.     {  
  206.         if (file.isDirectory() && !ArrayUtils.isEmpty(file.list()))  
  207.         {  
  208.             for (File childFile : file.listFiles())  
  209.             {  
  210.                 deleteAll(childFile);  
  211.             }  
  212.         }  
  213.         else  
  214.         {  
  215.             file.delete();  
  216.         }  
  217.     }  
  218.   
  219.     /** *//**  
  220.      * 断开与远程服务器的连接  
  221.      * @throws IOException  
  222.      */    
  223.     public void disconnect() throws IOException{     
  224.         if(ftpClient.isConnected()){     
  225.             ftpClient.disconnect();     
  226.         }     
  227.     }     
  228.          
  229.     public static void main(String[] args) {     
  230.         FtpUtils myFtp = new FtpUtils();     
  231.         try {     
  232.             myFtp.connect();     
  233.             System.out.println(myFtp.download(”/央视走西口/新浪网/走西口24.mp4”“E:\\走西口242.mp4”“123”));     
  234.             myFtp.disconnect();     
  235.         } catch (IOException e) {     
  236.             System.out.println(”连接FTP出错:”+e.getMessage());     
  237.         }     
  238.     }   
  239.   
  240.   
  241.   
  242.         //使用: 下载文件  
  243.         FtpUtils ftpUtils = new FtpUtils();  
  244.         ftpUtils.connect();  
  245.         ftpUtils.download(fileUrl, directoryPath, filename);  
  246.         ftpUtils.disconnect();  
  247.   
  248.   
  249.   
  250.   
  251. }  
/**
 * 支持断点续传的FTP实用类 
 * 
 * @author chenxin
 * @version [版本号, 2012-5-21]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class FtpUtils  {

    private FTPClient ftpClient = null;
   private static final Logger logger = Logger.getLogger(FtpUtils.class);
   private String hostname;
   private String username;
   private String password;
   private int port;
   private static final String EPUB_DIR = "epub_file";

   public FtpUtils()
   {
       ftpClient = new FTPClient();
       username = ServerConfig.get("ftp/ftp-user", "");
       password = ServerConfig.get("ftp/ftp-password", "");
       hostname = ServerConfig.get("ftp/ftp-host", "");
       port = ServerConfig.getInt("ftp/ftp-port", 21);
//       {   
//           //设置将过程中使用到的命令输出到控制台   
//           ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));   
//       } 
   }  

   /**  
    * 连接到FTP服务器 
    * @param hostname 主机名 
    * @param port 端口 
    * @param username 用户名 
    * @param password 密码 
    * @return 是否连接成功 
    * @throws IOException 
    */  
   public boolean connect() throws IOException{  
       ftpClient.connect(hostname, port);   
       ftpClient.setControlEncoding(ServerConfig.get("ftp/ftp-charset", "GBK"));   
       if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){   
           if(ftpClient.login(username, password)){  
               // 设置被动模式
               ftpClient.enterLocalPassiveMode();
               // 设置以二进制方式传输
               ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
               return true;   
           }   
       }   
       disconnect();   
       return false;   
   }   

   public boolean reconnect() throws IOException
   {  
         disconnect();  
         ftpClient.connect(hostname, port);   
         ftpClient.setControlEncoding(ServerConfig.get("ftp/ftp-charset", "GBK"));   
         if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){   
             if(ftpClient.login(username, password)){  
                 // 设置被动模式
                 ftpClient.enterLocalPassiveMode();
                 // 设置以二进制方式传输
                 ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                 return true;   
             }   
         }   
         disconnect();   
         return false;   
 }   

 /**
  * 从FTP服务器上下载文件,上传百分比
  * @param remote
  * @param dir
  * @param fileName
  * @return
  * @throws IOException
  * @see [类、类#方法、类#成员]
  */
    public boolean download(String remote, String dir, String fileName)
        throws IOException
    {
        File file = new File(dir + File.separator + fileName);
        // 本地存在文件
        if (file.exists())
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("File is existsed.");
            }
            // 如果文件存在,但还未从FTP服务器上完全取下来,则需要等待
            Long initialSize = 0L;
            int i = 0;
            while (initialSize != file.length())
            {
                i++;
                initialSize = file.length();
                try
                {
                    Thread.sleep(100L);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }

            if (i > 1)
            {
                // 如果是刚下完的文件,则不需要再比对大小是否一致
                return true;
            }
        }

        Long localSize = file.length();
        File localDir = new File(dir);
        if (!localDir.exists())
        {
            localDir.mkdirs();
        }

        // 检查远程文件是否存在
        if (remote.startsWith("/"))
        {
            remote = remote.substring(1);
        }

        if (ftpClient.listNames(remote).length <= 0)
        {   
            // 文件不存在
            logger.error("Could not find file from ftp server: " + remote);
            return false;
        }

        // 计算远程文件大小
        String s = "SIZE " + remote + "\r\n";
        ftpClient.sendCommand(s);
        String s1 = ftpClient.getReplyString();
        Long remoteSize = Long.parseLong(s1.substring(3).trim());
        if (logger.isDebugEnabled())
        {
            logger.debug("localsize: " + localSize + ", remoteSize: " + remoteSize);
        }
        if (remoteSize.equals(localSize))
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("File's size not changed.");
            }
            return true;
        }
        else if (localSize != 0L)
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("File's size changed which needed re-download.");
            }
            //远程文件和本地文件大小不一致,则删除本地文件
            file.delete();
            //如果是EPUB书路径,则需要把解压过的临时文件也一并删除
            if (dir.indexOf(EPUB_DIR) > 0)
            {
                deleteAll(localDir);
            }
        }

        // 重连以回到根目录
        reconnect();
        OutputStream out = new FileOutputStream(file);
        InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("UTF-8"),
            ServerConfig.get("ftp/ftp-charset", "GBK")));
        if (logger.isDebugEnabled())
        {
            logger.debug("Begin to downloaded file from ftp.");
        }
        byte[] bytes = new byte[1024];
        int count;
        while ((count = in.read(bytes)) != -1)
        {
            out.write(bytes, 0, count);
        }
        if (logger.isDebugEnabled())
        {
            logger.debug("File has been downloaded from ftp successfully.");
        }
        in.close();
        out.close();
        boolean upNewStatus = ftpClient.completePendingCommand();
        if (upNewStatus)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    //递归删除文件夹
    private void deleteAll(File file)
    {
        if (file.isDirectory() && !ArrayUtils.isEmpty(file.list()))
        {
            for (File childFile : file.listFiles())
            {
                deleteAll(childFile);
            }
        }
        else
        {
            file.delete();
        }
    }

    /** *//** 
     * 断开与远程服务器的连接 
     * @throws IOException 
     */  
    public void disconnect() throws IOException{   
        if(ftpClient.isConnected()){   
            ftpClient.disconnect();   
        }   
    }   

    public static void main(String[] args) {   
        FtpUtils myFtp = new FtpUtils();   
        try {   
            myFtp.connect();   
            System.out.println(myFtp.download("/央视走西口/新浪网/走西口24.mp4", "E:\\走西口242.mp4", "123"));   
            myFtp.disconnect();   
        } catch (IOException e) {   
            System.out.println("连接FTP出错:"+e.getMessage());   
        }   
    } 



        //使用: 下载文件
        FtpUtils ftpUtils = new FtpUtils();
        ftpUtils.connect();
        ftpUtils.download(fileUrl, directoryPath, filename);
        ftpUtils.disconnect();




}


案例四

sun.net.ftp.FtpClient.,该类库主要提供了用于建立FTP连接的类。利用这些类的方法,编程人员可以远程登录到FTP服务器,列举该服务器上的目录,设置传输协议,以及传送文件。FtpClient类涵盖了几乎所有FTP的功能,FtpClient的实例变量保存了有关建立”代理”的各种信息。下面给出了这些实例变量。


直接给大家上代码,想要用功能的直接拿过来用接可以:

  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedReader;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.io.OutputStream;  
  10. import java.sql.Connection;  
  11. import java.sql.Statement;  
  12. import java.util.ArrayList;  
  13. import java.util.List;  
  14. import java.util.Vector;  
  15.   
  16. import org.apache.commons.net.ftp.FTPClient;  
  17. import org.apache.commons.net.ftp.FTPFile;  
  18. import org.apache.commons.net.ftp.FTPReply;  
  19.   
  20.   
  21.   
  22. public class TfpTools {  
  23.     //连接ftp  
  24.     private FTPClient ftpClient = null;  
  25. //    public static String ip = “117.21.208.37”;  
  26. //    public static int port = 21;  
  27. //    public static String username = “eftp”;  
  28. //    public static String password = “e1f2t3p4”;  
  29. //    public static String sub_path = ”/opt/tomcat/webapps/photocdn/msgdata/”;  
  30.     /** 
  31.      * 连接ftp 
  32.      */  
  33.     public void connectServer(String ip,int port,String username,String password,String sub_path) throws Exception {  
  34.         int i = 10;  
  35.         if (ftpClient == null) {  
  36.             int reply;  
  37.             while (i > 0) {  
  38.                 try {  
  39.                     ftpClient = new FTPClient();  
  40.                     if (port != 21)  
  41.                         ftpClient.connect(ip, port);  
  42.                     else  
  43.                         ftpClient.connect(ip);  
  44.                     ftpClient.login(username, password);  
  45.                     reply = ftpClient.getReplyCode();  
  46.                     if (!FTPReply.isPositiveCompletion(reply)) {  
  47.                         ftpClient.disconnect();  
  48.                     }  
  49.                     System.out.println(”sub_path==============”+sub_path);  
  50.                     // 对目录进行转换  
  51.                     if (ftpClient.changeWorkingDirectory(sub_path)) {  
  52.                     } else {  
  53.                         ftpClient.disconnect();  
  54.                         ftpClient = null;  
  55.                     }  
  56.                 } catch (Exception e) {    
  57.                     e.printStackTrace();  
  58.                     if (0 < i–) {  
  59.                         try {  
  60.                             Thread.sleep(10000);  
  61.                             continue;  
  62.                         } catch (Exception ex) {  
  63.                         }  
  64.                     }  
  65.                 }  
  66.                 i = 0;  
  67.             }  
  68.         }  
  69.     }  
  70.     /** 
  71.      * 文件上传 
  72.      * @param ip 
  73.      * @param port 
  74.      * @param username 
  75.      * @param password 
  76.      * @param sub_path                远程文件上传目录 
  77.      * @param localFilePath              本地文件存放路径、、 
  78.      * @param newFileName            远程生成的文件路径和文件名 
  79.      * @throws Exception 
  80.      */  
  81.     public void uploadFile(String ip,int port,String username,String password,String sub_path,String localFilePath, String newFileName)throws Exception {  
  82.     BufferedInputStream buffIn = null;  
  83.     try {  
  84.         connectServer(ip,port,username,password,sub_path);        //连接服务器  
  85.         System.out.println(”start upload”);  
  86.         buffIn = new BufferedInputStream(new FileInputStream(localFilePath));  
  87.         System.out.println(”find localFilePath success”);  
  88.         ftpClient.storeFile(newFileName, buffIn);  
  89.         System.out.println(”upload success”);  
  90.     } catch (Exception e) {  
  91.         e.printStackTrace();  
  92.         throw e;  
  93.     } finally {  
  94.         try {  
  95.             if (buffIn != null)  
  96.                 buffIn.close();  
  97.         } catch (Exception e) {  
  98.             e.printStackTrace();  
  99.         }  
  100.     }  
  101.     }  
  102.     /** 
  103.      *  
  104.      * Definition: 读取txt文件,存放到list中,以便于读取 
  105.      * author: xiehaoyu 
  106.      * Created date: 2013-6-14 
  107.      * @param readTxt 
  108.      * @return 
  109.      */  
  110.     public static List<String> readTxt(String readTxt){  
  111.         BufferedReader br = null;  
  112.         List<String> list = new ArrayList<String>();  
  113.         try {  
  114.             br = new BufferedReader(new InputStreamReader(new FileInputStream(      
  115.                     new File(readTxt))));  
  116.             String temp = br.readLine();  
  117.             while (temp != null) {  
  118.                 String[] str=temp.toString().trim().split(”\\|”);  
  119.                 for(String s : str){  
  120.                     if(!“”.equals(s))  
  121.                     list.add(s);  
  122.                 }  
  123.                 temp=br.readLine();  
  124.             }  
  125.             br.close();  
  126.         } catch (Exception e1) {  
  127.             e1.printStackTrace();  
  128.         }  
  129.          return list;  
  130.     }  
  131.     public void copyFile(String oldPath, String newPath) {  
  132.         try {  
  133.           int bytesum = 0;  
  134.           int byteread = 0;  
  135.           File oldfile = new File(oldPath);  
  136.           if (oldfile.exists()) { //文件存在时  
  137.             InputStream inStream = new FileInputStream(oldPath); //读入原文件  
  138.             FileOutputStream fs = new FileOutputStream(newPath);  
  139.             byte[] buffer = new byte[1444];  
  140.             while ( (byteread = inStream.read(buffer)) != -1) {  
  141.               bytesum += byteread; //字节数 文件大小  
  142.               System.out.println(bytesum);  
  143.               fs.write(buffer, 0, byteread);  
  144.             }  
  145.             inStream.close();  
  146.           }  
  147.         }  
  148.         catch (Exception e) {  
  149.           System.out.println(”复制单个文件操作出错”);  
  150.           e.printStackTrace();  
  151.   
  152.         }  
  153.   
  154.     }  
  155.       
  156.     public void delFile(String filePathAndName) {  
  157.         try {  
  158.           String filePath = filePathAndName;  
  159.           filePath = filePath.toString();  
  160.           java.io.File myDelFile = new java.io.File(filePath);  
  161.           myDelFile.delete();  
  162.         }  
  163.         catch (Exception e) {  
  164.           System.out.println(”删除文件操作出错”);  
  165.           e.printStackTrace();  
  166.         }  
  167.     }  
  168.       
  169.     /** 
  170.      * 文件下载。。 
  171.      * @param url                ftp ip 
  172.      * @param port                ftp端口 
  173.      * @param username             
  174.      * @param password 
  175.      * @param remotePath        下载路径 
  176.      * @param fileName            下载文件中包含什么文件名 
  177.      * @param localPath            本地存放路径 
  178.      * @return 
  179.      */  
  180.     public static boolean downFile(  
  181.              String url,  
  182.              int port,  
  183.              String username,  
  184.              String password,  
  185.              String remotePath,  
  186.              String fileName,  
  187.              String localPath){  
  188.      boolean success = false;  
  189.      FTPClient ftp = new FTPClient();  
  190.      try {  
  191.          int reply;  
  192.          ftp.connect(url, port);  
  193.          //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器   
  194.          ftp.login(username, password);//登录   
  195.          reply = ftp.getReplyCode();  
  196.          if (!FTPReply.isPositiveCompletion(reply)) {  
  197.          ftp.disconnect();  
  198.          return success;  
  199.          }  
  200.          ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录  
  201.          FTPFile[] fs = ftp.listFiles();  
  202.          TfpTools fu=new TfpTools();  
  203.          for(FTPFile ff:fs){  
  204.              if(ff.getName().contains(fileName)){  
  205.                  if(fu.ToDetermineWhetherAFileExists(ff.getName())){  
  206.                  File localFile = new File(localPath+“/”+ff.getName());  
  207.                  OutputStream is = new FileOutputStream(localFile);  
  208.                  ftp.retrieveFile(ff.getName(), is);  
  209.                  is.close();  
  210.                  }  
  211.                  }  
  212.          }  
  213.              ftp.logout();  
  214.              success = true;  
  215.         } catch (IOException e) {  
  216.                   e.printStackTrace();  
  217.               } finally {  
  218.                     if (ftp.isConnected()) {  
  219.                         try {  
  220.                              ftp.disconnect();  
  221.                          } catch (IOException ioe) {  
  222.                          }  
  223.                      }  
  224.                 }  
  225.                   return success;  
  226.     }   
  227.       
  228.     public boolean ToDetermineWhetherAFileExists(String fileName){  
  229.         boolean flag=true;  
  230.         Vector<String> v=new Vector<String>();  
  231.         v=GetTestXlsFileName(”c:/JX_jiekou/src/backups”);  
  232.         for(int i=0;i<v.size();i++){  
  233.             String str=(String)v.elementAt(i);  
  234.             if(str.equals(fileName)){  
  235.                 flag=false;  
  236.             }  
  237.         }  
  238.         return flag;  
  239.     }  
  240.     /** 
  241.      * 读取本地某个目录下,所有txt文件的文件名 
  242.      * @param fileAbsolutePath        本地文件目录。 
  243.      * @return 
  244.      */  
  245.     public static Vector<String> GetTestXlsFileName(String fileAbsolutePath) {  
  246.         Vector<String> vecFile = new Vector<String>();  
  247.         File file = new File(fileAbsolutePath);  
  248.         File[] subFile = file.listFiles();  
  249.    
  250.         for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {  
  251.            // 判断是否为文件夹   
  252.            if (!subFile[iFileLength].isDirectory()) {  
  253.                String fileName = subFile[iFileLength].getName();  
  254.                // 判断是否为.txt结尾   
  255.                 if (fileName.trim().toLowerCase().endsWith(“.txt”)) {  
  256.                    vecFile.add(fileName);  
  257.                 }  
  258.            }  
  259.        }  
  260.         return vecFile;  
  261.    }  
  262.       
  263.     public boolean truncateTable(String tableName){  
  264.         Connection conn=null;  
  265.         Statement sm=null;  
  266.         String sql=”truncate table ”+tableName;  
  267.         try {  
  268.             conn=DBConfig.getConn(JkConfig.getDb_url(),JkConfig.getDb_username(),JkConfig.getDb_password(),0);  
  269.             sm=conn.createStatement();  
  270.             sm.executeUpdate(sql);  
  271.         } catch (Exception e) {  
  272.             e.printStackTrace();  
  273.         }  
  274.     return true;  
  275.     }  
  276.     public void closeConnect() {  
  277.         try {  
  278.             if (ftpClient != null) {  
  279.                 ftpClient.logout();  
  280.                 ftpClient.disconnect();  
  281.                 ftpClient=null;  
  282.             }  
  283.         } catch (Exception e) {  
  284.             e.printStackTrace();  
  285.         }  
  286.     }  
  287. }  
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;



public class TfpTools {
    //连接ftp
    private FTPClient ftpClient = null;
//    public static String ip = "117.21.208.37";
//    public static int port = 21;
//    public static String username = "eftp";
//    public static String password = "e1f2t3p4";
//    public static String sub_path = "/opt/tomcat/webapps/photocdn/msgdata/";
    /**
     * 连接ftp
     */
    public void connectServer(String ip,int port,String username,String password,String sub_path) throws Exception {
        int i = 10;
        if (ftpClient == null) {
            int reply;
            while (i > 0) {
                try {
                    ftpClient = new FTPClient();
                    if (port != 21)
                        ftpClient.connect(ip, port);
                    else
                        ftpClient.connect(ip);
                    ftpClient.login(username, password);
                    reply = ftpClient.getReplyCode();
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        ftpClient.disconnect();
                    }
                    System.out.println("sub_path=============="+sub_path);
                    // 对目录进行转换
                    if (ftpClient.changeWorkingDirectory(sub_path)) {
                    } else {
                        ftpClient.disconnect();
                        ftpClient = null;
                    }
                } catch (Exception e) {  
                    e.printStackTrace();
                    if (0 < i--) {
                        try {
                            Thread.sleep(10000);
                            continue;
                        } catch (Exception ex) {
                        }
                    }
                }
                i = 0;
            }
        }
    }
    /**
     * 文件上传
     * @param ip
     * @param port
     * @param username
     * @param password
     * @param sub_path                远程文件上传目录
     * @param localFilePath              本地文件存放路径、、
     * @param newFileName            远程生成的文件路径和文件名
     * @throws Exception
     */
    public void uploadFile(String ip,int port,String username,String password,String sub_path,String localFilePath, String newFileName)throws Exception {
    BufferedInputStream buffIn = null;
    try {
        connectServer(ip,port,username,password,sub_path);        //连接服务器
        System.out.println("start upload");
        buffIn = new BufferedInputStream(new FileInputStream(localFilePath));
        System.out.println("find localFilePath success");
        ftpClient.storeFile(newFileName, buffIn);
        System.out.println("upload success");
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        try {
            if (buffIn != null)
                buffIn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    }
    /**
     * 
     * Definition: 读取txt文件,存放到list中,以便于读取
     * author: xiehaoyu
     * Created date: 2013-6-14
     * @param readTxt
     * @return
     */
    public static List<String> readTxt(String readTxt){
        BufferedReader br = null;
        List<String> list = new ArrayList<String>();
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(    
                    new File(readTxt))));
            String temp = br.readLine();
            while (temp != null) {
                String[] str=temp.toString().trim().split("\\|");
                for(String s : str){
                    if(!"".equals(s))
                    list.add(s);
                }
                temp=br.readLine();
            }
            br.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
         return list;
    }
    public void copyFile(String oldPath, String newPath) {
        try {
          int bytesum = 0;
          int byteread = 0;
          File oldfile = new File(oldPath);
          if (oldfile.exists()) { //文件存在时
            InputStream inStream = new FileInputStream(oldPath); //读入原文件
            FileOutputStream fs = new FileOutputStream(newPath);
            byte[] buffer = new byte[1444];
            while ( (byteread = inStream.read(buffer)) != -1) {
              bytesum += byteread; //字节数 文件大小
              System.out.println(bytesum);
              fs.write(buffer, 0, byteread);
            }
            inStream.close();
          }
        }
        catch (Exception e) {
          System.out.println("复制单个文件操作出错");
          e.printStackTrace();

        }

    }

    public void delFile(String filePathAndName) {
        try {
          String filePath = filePathAndName;
          filePath = filePath.toString();
          java.io.File myDelFile = new java.io.File(filePath);
          myDelFile.delete();
        }
        catch (Exception e) {
          System.out.println("删除文件操作出错");
          e.printStackTrace();
        }
    }

    /**
     * 文件下载。。
     * @param url                ftp ip
     * @param port                ftp端口
     * @param username            
     * @param password
     * @param remotePath        下载路径
     * @param fileName            下载文件中包含什么文件名
     * @param localPath            本地存放路径
     * @return
     */
    public static boolean downFile(
             String url,
             int port,
             String username,
             String password,
             String remotePath,
             String fileName,
             String localPath){
     boolean success = false;
     FTPClient ftp = new FTPClient();
     try {
         int reply;
         ftp.connect(url, port);
         //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 
         ftp.login(username, password);//登录 
         reply = ftp.getReplyCode();
         if (!FTPReply.isPositiveCompletion(reply)) {
         ftp.disconnect();
         return success;
         }
         ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
         FTPFile[] fs = ftp.listFiles();
         TfpTools fu=new TfpTools();
         for(FTPFile ff:fs){
             if(ff.getName().contains(fileName)){
                 if(fu.ToDetermineWhetherAFileExists(ff.getName())){
                 File localFile = new File(localPath+"/"+ff.getName());
                 OutputStream is = new FileOutputStream(localFile);
                 ftp.retrieveFile(ff.getName(), is);
                 is.close();
                 }
                 }
         }
             ftp.logout();
             success = true;
        } catch (IOException e) {
                  e.printStackTrace();
              } finally {
                    if (ftp.isConnected()) {
                        try {
                             ftp.disconnect();
                         } catch (IOException ioe) {
                         }
                     }
                }
                  return success;
    } 

    public boolean ToDetermineWhetherAFileExists(String fileName){
        boolean flag=true;
        Vector<String> v=new Vector<String>();
        v=GetTestXlsFileName("c:/JX_jiekou/src/backups");
        for(int i=0;i<v.size();i++){
            String str=(String)v.elementAt(i);
            if(str.equals(fileName)){
                flag=false;
            }
        }
        return flag;
    }
    /**
     * 读取本地某个目录下,所有txt文件的文件名
     * @param fileAbsolutePath        本地文件目录。
     * @return
     */
    public static Vector<String> GetTestXlsFileName(String fileAbsolutePath) {
        Vector<String> vecFile = new Vector<String>();
        File file = new File(fileAbsolutePath);
        File[] subFile = file.listFiles();

        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
           // 判断是否为文件夹 
           if (!subFile[iFileLength].isDirectory()) {
               String fileName = subFile[iFileLength].getName();
               // 判断是否为.txt结尾 
                if (fileName.trim().toLowerCase().endsWith(".txt")) {
                   vecFile.add(fileName);
                }
           }
       }
        return vecFile;
   }

    public boolean truncateTable(String tableName){
        Connection conn=null;
        Statement sm=null;
        String sql="truncate table "+tableName;
        try {
            conn=DBConfig.getConn(JkConfig.getDb_url(),JkConfig.getDb_username(),JkConfig.getDb_password(),0);
            sm=conn.createStatement();
            sm.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    return true;
    }
    public void closeConnect() {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
                ftpClient=null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


案例二:
案例二:
案例二:
document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil(new Date()/3600000)
    <div id="digg" articleid="24458469">
        <dl id="btnDigg" class="digg digg_disable" onclick="btndigga();">

             <dt>顶</dt>
            <dd>0</dd>
        </dl>


        <dl id="btnBury" class="digg digg_disable" onclick="btnburya();">

              <dt>踩</dt>
            <dd>0</dd>               
        </dl>

    </div>
 <div class="tracking-ad" data-mod="popu_222"><a href="javascript:void(0);" target="_blank">&nbsp;</a>   </div>
<div class="tracking-ad" data-mod="popu_223"> <a href="javascript:void(0);" target="_blank">&nbsp;</a></div>
<script type="text/javascript">
            function btndigga() {
                $(".tracking-ad[data-mod='popu_222'] a").click();
            }
            function btnburya() {
                $(".tracking-ad[data-mod='popu_223'] a").click();
            }
        </script>

<div style="clear:both; height:10px;"></div>


        <div class="similar_article">
                <h4></h4>
                <div class="similar_c" style="margin:20px 0px 0px 0px">
                    <div class="similar_c_t">
                      &nbsp;&nbsp;相关文章推荐
                    </div>

                    <div class="similar_wrap tracking-ad" data-mod="popu_36">                       
                        <ul class="similar_list fl">    
                        </ul>
                          <ul class="similar_list fr">      
                        </ul>
                    </div>
                </div>
            </div>   
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
链接到sFTP客户端谷歌浏览器应用程序 访问您的本地/远程FTP服务器(包括您的NAS驱动器),本地服务器,VPS,专用服务器,云服务器或共享主机。 我们现在已经发布了适用于MAC,WINDOWS和LINUX的本地应用程序,请访问我们的网站: http://www.sftpclient.io/download ------------------------------------------ sFTP客户端是简单的,它是建立在谷歌浏览器/ Chrome操作系统打包的应用程序界面,使应用程序快速和响应。其中一些功能包括一个FTP / SFTP帐户管理器,用于存储和管理最常用和最喜欢的FTP / SFTP连接,只需点击一下,文件/文件夹队列即可查看当前正在上传/下载的项目,强大的文本编辑器(所以你甚至不需要额外的程序来修改你的代码),等等... 看看下面的sFTP客户端应用程序的所有功能。 特征: ========= - 标准的FTP连接 - SSH over File Transfer Protocol(sFTP)连接 - 用于SSH连接的权限密钥文件(SSH密钥 - RSA) - FTP / SFTP被动模式 - 连接到远程(外部)和本地(内部)FTP / SFTP / SSH服务器。 - 更改文件/文件夹权限(通过复选框或值:例如777) - 上传/下载多个文件文件夹 - 快速连接 - 编辑器选项:选项卡式文件,自定义 - 拖放文件/文件夹 - 管理FTP / SFTP / SSH账户(使用谷歌浏览器本地存储和安全密码加密存储) - 强大的文本编辑器,语法高亮(保存,自动保存和自动上传功能) - 键盘选择(向上,向下,进入(回车)和退出(退格)的目录,包括搜索能力,通过键盘上键入快速访问文件/文件夹) - 导入帐户:sFTP客户端 - 出口帐户 - 重命名和删除文件 - 创建新的文件/目录 - 刷新本地和远程列表 - 对列进行排序和调整大小 - 多选文件文件夹 - 按路径浏览本地和远程文件夹 - 本地目录:选择每个连接的默认本地目录,假设为全局 - 快速帐户菜单(一键从您保存的列表中打开FTP / SFTP / SSH帐户连接) - 多个FTP / SFTP / SSH帐户连接(如果您打开了大量连接,则滚动选项卡) - 关闭连接(断开与服务器的连接并删除所有活动) - 控制台日志(显示所有FTP / SFTP / SSH活动日志) - 传输队列(排队的文件文件夹,失败的文件文件夹,完成的文件文件夹) - 新的Google Sockets API - 远程和本地菜单 - 连接并列出UNIX和MS-DOS目录 - 复制网址到剪贴板 - 10最近的连接 - 保持连接 - 主密码登录(保持所有的FTP连接安全,1登录) - 同步浏览 更多的功能和功能来免费未来的更新! 支持语言:English (UK)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值