zoukankan      html  css  js  c++  java
  • ftp链接、上传、下载、断开

     开发环境:Jdk 1.8

      引入第三方库:commons-net-2.2.jar(针对第一种方法)

    一、基于第三方库FtpClient的FTP服务器数据传输

      由于是基于第三方库,所以这里基本上没有太多要说明的东西。就是导入第三方库再调用即可,调用过程从下面的代码可以参见。为了便于文章的完整性,这也是给出其程序结构图吧。

    图-1 基于FtpClient的FTP网络文件传输图

     所需要

    commons.net-1.4.1.jar

    jar包已保存到百度网盘ftptest中。或者http://pan.baidu.com/s/1hq5p7NI

    
    

    /**
    * ftp链接常量
    *
    */
    public class Ftp {

    
    

    private String ipAddr;//ip地址

    private Integer port;//端口号

    private String userName;//用户名

    private String pwd;//密码

    private String path;//aaa路径

    
    

    public String getIpAddr() {
    return ipAddr;
    }

    
    

    public void setIpAddr(String ipAddr) {
    this.ipAddr = ipAddr;
    }

    
    

    public Integer getPort() {
    return port;
    }

    
    

    public void setPort(Integer port) {
    this.port = port;
    }

    
    

    public String getUserName() {
    return userName;
    }

    
    

    public void setUserName(String userName) {
    this.userName = userName;
    }

    
    

    public String getPwd() {
    return pwd;
    }

    
    

    public void setPwd(String pwd) {
    this.pwd = pwd;
    }

    
    

    public String getPath() {
    return path;
    }

    
    

    public void setPath(String path) {
    this.path = path;
    }


    }

     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.net.ftp.FTPFile;
    import org.apache.commons.net.ftp.FTPReply;
    import org.apache.log4j.Logger;
    
    public class FtpUtil {
        
        private static Logger logger=Logger.getLogger(FtpUtil.class);
        
        private static FTPClient ftp;
        
        /**
         * 获取ftp连接
         * @param f
         * @return
         * @throws Exception
         */
        public static boolean connectFtp(Ftp f) throws Exception{
            ftp=new FTPClient();
            boolean flag=false;
            int reply;
            if (f.getPort()==null) {
                ftp.connect(f.getIpAddr(),21);
            }else{
                ftp.connect(f.getIpAddr(),f.getPort());
            }
            ftp.login(f.getUserName(), f.getPwd());
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            reply = ftp.getReplyCode();      
            if (!FTPReply.isPositiveCompletion(reply)) {      
                  ftp.disconnect();      
                  return flag;      
            }      
            ftp.changeWorkingDirectory(f.getPath());      
            flag = true;      
            return flag;
        }
        
        /**
         * 关闭ftp连接
         */
        public static void closeFtp(){
            if (ftp!=null && ftp.isConnected()) {
                try {
                    ftp.logout();
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        /**
         * ftp上传文件
         * @param f
         * @throws Exception
         */
        public static void upload(File f) throws Exception{
            if (f.isDirectory()) {
                ftp.makeDirectory(f.getName());
                ftp.changeWorkingDirectory(f.getName());
                String[] files=f.list();
                for(String fstr : files){
                    File file1=new File(f.getPath()+"/"+fstr);
                    if (file1.isDirectory()) {
                        upload(file1);
                        ftp.changeToParentDirectory();
                    }else{
                        File file2=new File(f.getPath()+"/"+fstr);
                        FileInputStream input=new FileInputStream(file2);
                        ftp.storeFile(file2.getName(),input);
                        input.close();
                    }
                }
            }else{
                File file2=new File(f.getPath());
                FileInputStream input=new FileInputStream(file2);
                ftp.storeFile(file2.getName(),input);
                input.close();
            }
        }
        
        /**
         * 下载链接配置
         * @param f
         * @param localBaseDir 本地目录
         * @param remoteBaseDir 远程目录
         * @throws Exception
         */
        public static void startDown(Ftp f,String localBaseDir,String remoteBaseDir ) throws Exception{
            if (FtpUtil.connectFtp(f)) {
                
                try { 
                    FTPFile[] files = null; 
                    boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir); 
                    if (changedir) { 
                        ftp.setControlEncoding("GBK"); 
                        files = ftp.listFiles(); 
                        for (int i = 0; i < files.length; i++) { 
                            try{ 
                                downloadFile(files[i], localBaseDir, remoteBaseDir); 
                            }catch(Exception e){ 
                                logger.error(e); 
                                logger.error("<"+files[i].getName()+">下载失败"); 
                            } 
                        } 
                    } 
                } catch (Exception e) { 
                    logger.error(e); 
                    logger.error("下载过程中出现异常"); 
                } 
            }else{
                logger.error("链接失败!");
            }
            
        }
        
        
        /** 
         * 
         * 下载FTP文件 
         * 当你需要下载FTP文件的时候,调用此方法 
         * 根据<b>获取的文件名,本地地址,远程地址</b>进行下载 
         * 
         * @param ftpFile 
         * @param relativeLocalPath 
         * @param relativeRemotePath 
         */ 
        private  static void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) { 
            if (ftpFile.isFile()) {
                if (ftpFile.getName().indexOf("?") == -1) { 
                    OutputStream outputStream = null; 
                    try { 
                        File locaFile= new File(relativeLocalPath+ ftpFile.getName()); 
                        //判断文件是否存在,存在则返回 
                        if(locaFile.exists()){ 
                            return; 
                        }else{ 
                            outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName()); 
                            ftp.retrieveFile(ftpFile.getName(), outputStream); 
                            outputStream.flush(); 
                            outputStream.close(); 
                        } 
                    } catch (Exception e) { 
                        logger.error(e);
                    } finally { 
                        try { 
                            if (outputStream != null){ 
                                outputStream.close(); 
                            }
                        } catch (IOException e) { 
                           logger.error("输出文件流异常"); 
                        } 
                    } 
                } 
            } else { 
                String newlocalRelatePath = relativeLocalPath + ftpFile.getName(); 
                String newRemote = new String(relativeRemotePath+ ftpFile.getName().toString()); 
                File fl = new File(newlocalRelatePath); 
                if (!fl.exists()) { 
                    fl.mkdirs(); 
                } 
                try { 
                    newlocalRelatePath = newlocalRelatePath + '/'; 
                    newRemote = newRemote + "/"; 
                    String currentWorkDir = ftpFile.getName().toString(); 
                    boolean changedir = ftp.changeWorkingDirectory(currentWorkDir); 
                    if (changedir) { 
                        FTPFile[] files = null; 
                        files = ftp.listFiles(); 
                        for (int i = 0; i < files.length; i++) { 
                            downloadFile(files[i], newlocalRelatePath, newRemote); 
                        } 
                    } 
                    if (changedir){
                        ftp.changeToParentDirectory(); 
                    } 
                } catch (Exception e) { 
                    logger.error(e);
                } 
            } 
        } 
    
        
        public static void main(String[] args) throws Exception{  
                Ftp f=new Ftp();
                f.setIpAddr("1111");
                f.setUserName("root");
                f.setPwd("111111");
                FtpUtil.connectFtp(f);
                File file = new File("F:/test/com/test/Testng.java");  
                FtpUtil.upload(file);//把文件上传在ftp上
                FtpUtil.startDown(f, "e:/",  "/xxtest");//下载ftp文件测试
                System.out.println("ok");
              
           }  
        
    }

    1.FTP的连接及登录

     
    1. public static FtpClient connectFTP(String url, int port, String username, String password) {  
    2.         //创建ftp  
    3.         FtpClient ftp = null;  
    4.         try {  
    5.             //创建地址  
    6.             SocketAddress addr = new InetSocketAddress(url, port);  
    7.             //连接  
    8.             ftp = FtpClient.create();  
    9.             ftp.connect(addr);  
    10.             //登陆  
    11.             ftp.login(username, password.toCharArray());  
    12.             ftp.setBinaryType();  
    13.         } catch (FtpProtocolException e) {  
    14.             e.printStackTrace();  
    15.         } catch (IOException e) {  
    16.             e.printStackTrace();  
    17.         }  
    18.         return ftp;  
    19.     }  

    2.上传文件到FTP服务器

     
    1. public static void upload(String localFile, String ftpFile, FtpClient ftp) {  
    2.         OutputStream os = null;  
    3.         FileInputStream fis = null;  
    4.         try {  
    5.             // 将ftp文件加入输出流中。输出到ftp上  
    6.             os = ftp.putFileStream(ftpFile);  
    7.             File file = new File(localFile);  
    8.   
    9.             // 创建一个缓冲区  
    10.             fis = new FileInputStream(file);  
    11.             byte[] bytes = new byte[1024];  
    12.             int c;  
    13.             while((c = fis.read(bytes)) != -1){  
    14.                 os.write(bytes, 0, c);  
    15.             }  
    16.             System.out.println("upload success!!");  
    17.         } catch (FtpProtocolException e) {  
    18.             e.printStackTrace();  
    19.         } catch (IOException e) {  
    20.             e.printStackTrace();  
    21.         } finally {  
    22.             try {  
    23.                 if(os!=null) {  
    24.                     os.close();  
    25.                 }  
    26.                 if(fis!=null) {  
    27.                     fis.close();  
    28.                 }  
    29.             } catch (IOException e) {  
    30.                 e.printStackTrace();  
    31.             }  
    32.         }  
    33.     }  

    3.从FTP服务器下载文件

     
    1. public static void download(String localFile, String ftpFile, FtpClient ftp) {  
    2.         InputStream is = null;  
    3.         FileOutputStream fos = null;  
    4.         try {  
    5.             // 获取ftp上的文件  
    6.             is = ftp.getFileStream(ftpFile);  
    7.             File file = new File(localFile);  
    8.             byte[] bytes = new byte[1024];  
    9.             int i;  
    10.             fos = new FileOutputStream(file);  
    11.             while((i = is.read(bytes)) != -1){  
    12.                 fos.write(bytes, 0, i);  
    13.             }  
    14.             System.out.println("download success!!");  
    15.   
    16.         } catch (FtpProtocolException e) {  
    17.             e.printStackTrace();  
    18.         } catch (IOException e) {  
    19.             e.printStackTrace();  
    20.         } finally {  
    21.             try {  
    22.                 if(fos!=null) {  
    23.                     fos.close();  
    24.                 }  
    25.                 if(is!=null){  
    26.                     is.close();  
    27.                 }  
    28.             } catch (IOException e) {  
    29.                 e.printStackTrace();  
    30.             }  
    31.         }  
    32.     }  

      

    二、基于Socket的FTP服务器数据传输

      其实上面的基于第三方包FtpClient的方法中,原理层也是基于Socket来进行通信的。所以,我们当然也可以使用Socket直接来写这个FtpClient的代码。下面给出基于Socket通信的结构构架图。这里有一点需要大家注意一下,我们的FTP协议中有两个端口(20和21)。通常情况下,我们的21号端口就是平时大家口口相传的是FTP服务器的端口号,不过其实它只是FTP服务器中的命令端口号。它是负责传送命令给FTP,一些操作如“登录”、“改变目录”、“删除文件”,依靠这个连接发送命令就可完成。而对于20号端口号(也有可能是其它的一些端口号),对于有数据传输的操作,主要是显示目录列表,上传、下载文件,我们需要依靠另一个Socket来完成。

      所以在下面的结构图中,我们可以看到我们有重新获得端口号的过程,正是这个原因。

    图-2 基于Socket的FTP网络文件传输图

    1.FTP连接

     
    1. public void connectFtp() {  
    2.         try {  
    3.             mFtpClient = new Socket(Config.FTP.HOST_IP, Config.FTP.HOST_PORT);  
    4.             mReader = new BufferedReader(new InputStreamReader(mFtpClient.getInputStream()));  
    5.             mWriter = new BufferedWriter(new OutputStreamWriter(mFtpClient.getOutputStream()));  
    6.   
    7.             sendCommand("USER " + Config.FTP.FTP_USERNAME);  
    8.             sendCommand("PASS " + Config.FTP.FTP_PASSWD);  
    9.         } catch (IOException e) {  
    10.             e.printStackTrace();  
    11.         }  
    12.     }  

    2.向FTP服务器发送命令

     
    1. private void sendCommand(String command) throws IOException {  
    2.         if (Tools.StringTools.isEmpty(command)) {  
    3.             return;  
    4.         }  
    5.   
    6.         if (mFtpClient == null) {  
    7.             return;  
    8.         }  
    9.   
    10.         mWriter.write(command + " ");  
    11.         mWriter.flush();  
    12.     }  

    3.向FTP服务器上传文件

     
    1. public void uploadFile(String localPath, String ftpPath) throws IOException {  
    2.         // 进入被动模式  
    3.         sendCommand("PASV");  
    4.   
    5.         // 获得ip和端口  
    6.         String response = readNewMessage();  
    7.         String[] ipPort = getIPPort(response);  
    8.         String ip = ipPort[0];  
    9.         int port = Integer.parseInt(ipPort[1]);  
    10.   
    11.         // 建立数据端口的连接  
    12.         Socket dataSocket = new Socket(ip, port);  
    13.         sendCommand("STOR " + ftpPath);  
    14.   
    15.         // 上传文件前的准备  
    16.         File localFile = new File(localPath);  
    17.         OutputStream outputStream = dataSocket.getOutputStream();  
    18.         FileInputStream fileInputStream = new FileInputStream(localFile);  
    19.   
    20.         // 上传文件  
    21.         int offset;  
    22.         byte[] bytes = new byte[1024];  
    23.         while ((offset = fileInputStream.read(bytes)) != -1) {  
    24.             outputStream.write(bytes, 0, offset);  
    25.         }  
    26.         System.out.println("upload success!!");  
    27.   
    28.         // 上传文件后的善后工作  
    29.         outputStream.close();  
    30.         fileInputStream.close();  
    31.         dataSocket.close();  
    32.     }  

    4.从FTP服务器下载文件

    [java] view plain copy
     
     print?
    1. public void downloadFile(String localPath, String ftpPath) throws IOException {  
    2.         // 进入被动模式  
    3.         sendCommand("PASV");  
    4.   
    5.         // 获得ip和端口  
    6.         String response = readNewMessage();  
    7.         String[] ipPort = getIPPort(response);  
    8.         String ip = ipPort[0];  
    9.         int port = Integer.parseInt(ipPort[1]);  
    10.   
    11.         // 建立数据端口的连接  
    12.         Socket dataSocket = new Socket(ip, port);  
    13.         sendCommand("RETR " + ftpPath);  
    14.   
    15.         // 下载文件前的准备  
    16.         File localFile = new File(localPath);  
    17.         InputStream inputStream = dataSocket.getInputStream();  
    18.         FileOutputStream fileOutputStream = new FileOutputStream(localFile);  
    19.   
    20.         // 下载文件  
    21.         int offset;  
    22.         byte[] bytes = new byte[1024];  
    23.         while ((offset = inputStream.read(bytes)) != -1) {  
    24.             fileOutputStream.write(bytes, 0, offset);  
    25.         }  
    26.         System.out.println("download success!!");  
    27.   
    28.         // 下载文件后的善后工作  
    29.         inputStream.close();  
    30.         fileOutputStream.close();  
    31.         dataSocket.close();  
    32.     }  

    5.断开FTP服务器连接

    [java] view plain copy
     
     print?
      1. public void disconnectFtp() {  
      2.         if (mFtpClient == null) {  
      3.             return;  
      4.         }  
      5.   
      6.         if (!mFtpClient.isConnected()) {  
      7.             return;  
      8.         }  
      9.   
      10.         try {  
      11.             mFtpClient.close();  
      12.         } catch (IOException e) {  
      13.             e.printStackTrace();  
      14.         }  
      15.     }  
  • 相关阅读:
    性格-汉语-词语:坚忍
    汉语-词语:坚强
    品质-汉语-成语:坚持不懈
    was系统错误日志大量出现标识符缺失
    【iOS】UIWebView的HTML5扩展之canvas篇
    OA权限树搭建 代码
    linux下的环境文件设置说明
    怎样把多个Android Project打包成一个APK
    nyoj43 24 Point game(DFS)
    【西祠日志】【07】努力努力,找资料,思考,怎么做asp图片上传
  • 原文地址:https://www.cnblogs.com/zipon/p/6072063.html
Copyright © 2011-2022 走看看