ftp文件下载

链接ftp,并从ftp上面下载文件

 

调用方法:

package ftp;

import java.io.File;
import java.io.IOException;

import pojo.FileFtp;

public class Test {
    public static void main(String[] args) throws Exception {
        getRemotoFtpAllFileName();
    }
    
    //获取FTP目录下的所有文件夹
    public static void getRemotoFtpAllFileName() {
        Ftp ftp=new Ftp();
        ftp.setIpAddr("1.1.1.217");
        ftp.setPort(21);
        ftp.setUserName("zangsan");
        ftp.setPwd("123");
        ftp.setPath("/home/zangsan/tmp");
        
        /*
        //文件上传
        File file=new File("C:\\Users\\doume\\Desktop\\问责率调用方法.txt");
        FtpUtil.upload(ftp,file);
        */
        
        try {
            FtpUtil.startDown(ftp,"C:\\Users\\doume\\Desktop\\拦截器验证token\\filedown\\test","/home/zangsan/tmp");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("success");
    }
}

 

 

 

一共有三个类:

package ftp;

public class Ftp {

    private String ipAddr;
    
    private Integer port;
    
    private String userName;
    
    private String pwd;
    
    private String path;

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

 

package ftp;
import java.io.File;  
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.net.ftp.FTPClient;  
import org.apache.commons.net.ftp.FTPReply;  
  
public class FTPRemo {    
     
    public FTPRemo(String path,String addr,int port,String username,String password ) {
        try {
            connect(path,addr,port,username,password );
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("ftp连接失败,IP: "+addr+",port: "+port);
            e.printStackTrace();
        }
          
    }


    private  FTPClient ftp;    
    /** 
     *  
     * @param path     
     * @param addr 
     * @param port 
     * @param username 
     * @param password 
     * @return 
     * @throws Exception 
     */  
    public  boolean connect(String path,String addr,int port,String username,String password) throws Exception {    
        boolean result = false;    
        ftp = new FTPClient();    
        int reply;   
        ftp.connect(addr,port);    
        ftp.login(username,password);    
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);    
        reply = ftp.getReplyCode();    
        if (!FTPReply.isPositiveCompletion(reply)) {    
            ftp.disconnect();    
            return result;    
        }    
        ftp.changeWorkingDirectory(path);    
        result = true;    
        return result;    
    }    
    /** 
     *  
     * @param file 文件上传
     * @throws Exception 
     */  
    public void upload(File file) throws Exception{    
        if(file.isDirectory()){         
            ftp.makeDirectory(file.getName());              
            ftp.changeWorkingDirectory(file.getName());    
            String[] files = file.list();           
            for (int i = 0; i < files.length; i++) {    
                File file1 = new File(file.getPath()+"\\"+files[i] );    
                if(file1.isDirectory()){    
                    upload(file1);    
                    ftp.changeToParentDirectory();    
                }else{                  
                    File file2 = new File(file.getPath()+"\\"+files[i]);    
                    FileInputStream input = new FileInputStream(file2);    
                    ftp.storeFile(file2.getName(), input);    
                    input.close();                          
                }               
            }    
        }else{    
            File file2 = new File(file.getPath());    
            FileInputStream input = new FileInputStream(file2);  
            String name=new String(file2.getName().getBytes(),"iso-8859-1");
            ftp.storeFile(name, input);    
            input.close();      
        }    
    } 
    
    
/*   public static void main(String[] args) throws Exception{  
    FTPRemo t = new FTPRemo();  
    t.connect("/home/user-file", "192.168.31.92", 21, "user-file", "123");  
    File file = new File("F:/test_client.txt");  
    t.upload(file);  
    System.out.println("ok");
      
   }  */
}  

package ftp;

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(Ftp ftps,File f) throws Exception{
        if (FtpUtil.connectFtp(ftps)) {
            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(ftps,file1);
                        ftp.changeToParentDirectory();
                    }else{
                        File file2=new File(f.getPath()+"/"+fstr);
                        FileInputStream input=new FileInputStream(file2);
                        String name=new String(file2.getName().getBytes(),"iso-8859-1");
                        ftp.storeFile(name,input);
                        input.close();
                    }
                }
            }else{
                File file2=new File(f.getPath());
                FileInputStream input=new FileInputStream(file2);
                String name=new String(file2.getName().getBytes(),"iso-8859-1");
                ftp.storeFile(name, input);  
                input.close();
            }
        }else{
            logger.error("链接失败");
        }
    }
    
    /**
     * 下载链接配置
     * @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("utf-8"); 
                    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+ File.separator+ftpFile.getName()); 
                    //判断文件是否存在,存在则返回 
                    if(locaFile.exists()){ 
                        return; 
                    }else{ 
                        outputStream = new FileOutputStream(relativeLocalPath+ File.separator+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 +File.separator+ ftpFile.getName(); 
            System.out.println(newlocalRelatePath);
            String newRemote = new String(relativeRemotePath+ File.separator+ftpFile.getName().toString()); 
            System.out.println(newRemote);
            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{  
          
       }  
    
}

 

jar包:

 

posted @ 2022-08-16 15:26  王短腿  阅读(757)  评论(0编辑  收藏  举报