1. 程式人生 > >sftp,ftp檔案下載

sftp,ftp檔案下載

一、sftp工具類

package com.ztesoft.iotcmp.util;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import java.io.*;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List; import java.util.Properties; import java.util.Vector; import java.util.zip.GZIPInputStream; public class SftpUtil implements AutoCloseable { private Session session = null; private ChannelSftp channel = null; private String userName = "bi"; private String passWord = "bi";
private String hostName = "10.40.197.41"; private String port = ""; private String workDir = "test/download"; public SftpUtil(String hostName, String port, String userName , String passWord, String workDir) throws IOException, JSchException { this.hostName = hostName;
this.port = port; this.userName = userName; this.passWord = passWord; this.workDir = workDir; connectServer(hostName, Integer.parseInt(port), userName, passWord); } /** * 連線sftp伺服器 * * @param serverIP 服務IP * @param port 埠 * @param userName 使用者名稱 * @param password 密碼 * @throws SocketException SocketException * @throws IOException IOException * @throws JSchException JSchException */ public void connectServer(String serverIP, int port, String userName, String password) throws JSchException { JSch jsch = new JSch(); // 根據使用者名稱,主機ip,埠獲取一個Session物件 session = jsch.getSession(userName, serverIP, port); // 設定密碼 session.setPassword(password); // 為Session物件設定properties Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); // 通過Session建立連結 session.connect(); // 開啟SFTP通道 channel = (ChannelSftp) session.openChannel("sftp"); // 建立SFTP通道的連線 channel.connect(); } /** * 自動關閉資源 */ public void close() { if (channel != null) { channel.disconnect(); } if (session != null) { session.disconnect(); } } /** * @param path * @throws SftpException * @return獲取目錄下檔名稱 */ public List<String> getDirFileList(String path) throws SftpException { List<String> list = new ArrayList<>(); if (channel != null) { Vector vv = channel.ls(path); if (vv == null && vv.size() == 0) { return list; } else { Object[] aa = vv.toArray(); for (int i = 0; i < aa.length; i++) { System.out.print(aa[i].toString()); ChannelSftp.LsEntry temp = (ChannelSftp.LsEntry) aa[i]; //獲取檔名稱 String fileName = temp.getFilename(); //判斷檔名稱是否為點 if (!fileName.equals(".") && !fileName.equals("..")) { //判斷檔案是否為目錄 if (!temp.getAttrs().isDir()) { list.add(fileName); } } } } } return list; } /** * 下載檔案 * * @param remotePathFile 遠端檔案 * @param localPathFile 本地檔案[絕對路徑] * @throws SftpException SftpException * @throws IOException IOException */ public void downloadFile(String remotePathFile, String localPathFile) throws SftpException, IOException { try (FileOutputStream os = new FileOutputStream(new File(localPathFile))) { if (channel == null) throw new IOException("sftp server not login"); channel.get(remotePathFile, os); } } /** * 下載檔案 * * @param downloadFile 下載的檔案 * @param saveFile 存在本地的路徑 */ public void download(String downloadFile, String saveFile) throws SftpException, FileNotFoundException { if (workDir != null && !"".equals(workDir)) { channel.cd(workDir); } File file = new File(saveFile); channel.get(downloadFile, new FileOutputStream(file)); System.out.println("下載檔案到"+saveFile+"目錄完成!"); } /** * 下載檔案 * * @param downloadFile 下載的檔案 */ public InputStream download(String downloadFile) { InputStream in = null; try { channel.cd(workDir); in = channel.get(downloadFile); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } return in; } /** * 上傳檔案 * * @param remoteFile 遠端檔案 * @param localFile * @throws SftpException * @throws IOException */ public void uploadFile(String remoteFile, String localFile) throws SftpException, IOException { try (FileInputStream in = new FileInputStream(new File(localFile))) { if (channel == null) throw new IOException("sftp server not login"); channel.put(in, remoteFile); } } /** * 下載流檔案 * * @param remoteFileName * @return * @throws SftpException * @throws IOException */ public BufferedReader downloadGZFile(String remoteFileName) throws SftpException, IOException { BufferedReader returnValue = null; //跳轉目錄 Boolean state = openDir(this.workDir, channel); //判斷是否跳轉到指定目錄 if (state) { InputStream in = new GZIPInputStream(channel.get(remoteFileName)); if (in != null) { returnValue = new BufferedReader(new InputStreamReader(in)); System.out.println("<----------- INFO: download " + this.workDir + "/" + remoteFileName + " from ftp : succeed! ----------->"); } else { System.out.println("<----------- ERR : download " + this.workDir + "/" + remoteFileName + " from ftp : failed! ----------->"); } } return returnValue; } /** * 跳轉到指定的目錄 * * @param directory * @param sftp * @return */ public static boolean openDir(String directory, ChannelSftp sftp) { try { sftp.cd(directory); return true; } catch (SftpException e) { return false; } } public String getWorkDir() { return this.workDir; } }

 

二、檔案處理思想流程

獲取sftp連線

SftpUtil sftpUtil = new SftpUtil(host,port,userName,passWord,dir);

 

根據路徑獲取檔案列表

List<String> fileList = sftpUtil.getDirFileList(sftpUtil.getWorkDir());
if (fileList == null || fileList.isEmpty()) {
     throw new RuntimeException("沒有檔案要處理!");
}

 

判斷檔案是否處理過

boolean flag = SftpConfigUtil.checkFileIsDeal(fileName);//此處是根據表資料查詢

 

未處理,進行處理過程

if (!flag){
    BufferedReader reader = sftpUtil.downloadGZFile(fileName);//下載壓縮檔案並轉化為流

    List<TempPaymentDayAuditFileDTO> dataList = paseReader(reader, fileName);//解析檔案欄位,注意關閉檔案流reader.close();
tempPaymentDayAuditService.insertPaymentDayAudits(dataList);//插入資料庫 SftpConfigUtil.insertFileIsDeal(fileName);//插入檔案已處理標記到資料表中 }

 

關閉sftp連線

 sftpUtil.close();

 

三、ftp工具類

package com.ztesoft.iotcmp.util;

import org.apache.commons.io.IOUtils;
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;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPInputStream;

/**
 * Ftp操作工具類
 * 
 * @author easonwu 
 *
 */
public class FtpUtil {

    private  String userName = "bi";
    private  String passWord = "bi";
    private  String hostName = "10.40.197.41" ;
    private  String port = "" ;
    private  String workDir = "test/download" ;
    private  FTPClient ftpClient = new FTPClient();
    

    public FtpUtil() throws IOException {
        initailCheck() ;
    }
    
    public FtpUtil(String hostName , String port , String userName 
            , String passWord , String workDir) throws IOException {
        this.hostName = hostName ;
        this.port = port ;
        this.userName = userName ;
        this.passWord = passWord ;
        this.workDir = workDir ;
        initailCheck() ;
    }
    
    private void initailCheck() throws IOException {
        connectToServer();
        if( this.workDir != null && !"".endsWith(this.workDir )){
            checkPathExist(this.workDir);
        }
        closeConnect();
    }

    /** 
     * 查詢指定目錄是否存在 
     * @param  filePath 要查詢的目錄
     * @return boolean:存在:true,不存在:false 
     * @throws IOException 
     */
    private  boolean checkPathExist(String filePath) throws IOException {
        boolean existFlag = false;
        try {
            if (!ftpClient.changeWorkingDirectory(filePath)) {
                ftpClient.makeDirectory(filePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return existFlag;
    }

    /** 
     * 連線到ftp伺服器 
     */
    private void connectToServer() throws IOException{
        if(!ftpClient.isConnected()){
            int reply;
            try{
                ftpClient = new FTPClient();
                ftpClient.enterLocalPassiveMode();
                
                if(this.port == null || "".equals(this.port)){
                    ftpClient.connect(this.hostName);
                }
                else{
                    ftpClient.connect(this.hostName, Integer.parseInt(this.port));
                }
                
                ftpClient.login(userName, passWord);
                reply = ftpClient.getReplyCode();
                
                if(!FTPReply.isPositiveCompletion(reply)){
                    ftpClient.disconnect();
                    System.err.println("FTP server refused connection.");
                }
            }
            catch(IOException e){
//                System.err.println("登入ftp伺服器【" + this.hostName + "】失敗");
                e.printStackTrace();
                throw new IOException("登入ftp伺服器【" + this.hostName + "】失敗");
            }
        }
    }

    /** 
     * 關閉連線 
     */
    private  void closeConnect() {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 
     * 轉碼[GBK ->  ISO-8859-1] 
     * 不同的平臺需要不同的轉碼 
     * @param obj 
     * @return 
     */
    private static String gbkToIso8859(Object obj) {
        try {
            if (obj == null)
                return "";
            else
                return new String(obj.toString().getBytes("GBK"), "iso-8859-1");
        } catch (Exception e) {
            return "";
        }
    }

    /** 
     * 轉碼[ISO-8859-1 ->  GBK] 
     * 不同的平臺需要不同的轉碼 
     * @param obj 
     * @return 
     */
    private static String iso8859ToGbk(Object obj) {
        try {
            if (obj == null)
                return "";
            else
                return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
        } catch (Exception e) {
            return "";
        }
    }

    /** 
     * 設定傳輸檔案的型別[文字檔案或者二進位制檔案] 
     * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE 
     */
    private  void setFileType(int fileType) {
        try {
            ftpClient.setFileType(fileType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void changeDir(String filePath) throws IOException {
//        跳轉到指定的檔案目錄 
        if (filePath != null && !filePath.equals("")) {
            if (filePath.indexOf("/") != -1) {
                int index = 0;
                while ((index = filePath.indexOf("/")) != -1) {
                    System.out.println("P:"+ filePath.substring(0,
                            index)) ;
                    ftpClient.changeWorkingDirectory(filePath.substring(0,
                            index));

                    filePath = filePath.substring(index + 1, filePath.length());
                }
                if (!filePath.equals("") && !"/".equals(filePath)) {
                    ftpClient.changeWorkingDirectory(filePath);
                }
            } else {
                ftpClient.changeWorkingDirectory(filePath);
            }
        }
    }
    /**
     * check file 
     * @param filePath
     * @param fileName
     * @return
     * @throws IOException
     */
    private  boolean checkFileExist(String filePath, String fileName)
            throws IOException {
        boolean existFlag = false;
        changeDir( filePath )  ;
        String[] fileNames = ftpClient.listNames();
        if (fileNames != null && fileNames.length > 0) {
            for (int i = 0; i < fileNames.length; i++) {
                System.out.println("File:" + iso8859ToGbk(fileNames[i])) ;
                if (fileNames[i] != null
                        && iso8859ToGbk(fileNames[i]).equals(fileName)) {
                    existFlag = true;
                    break;
                }
            }
        }
        ftpClient.changeToParentDirectory();
        return existFlag;
    }

    /**
     * download ftp file as inputstream 
     * @param remoteFileName
     * @return
     * @throws IOException
     */
    public  InputStream downloadFile(
            String remoteFileName) throws IOException {
        InputStream returnValue = null;
        //下載檔案 
        BufferedOutputStream buffOut = null;
        try {
            //連線ftp伺服器 
            connectToServer();
            if (!checkFileExist(this.workDir, remoteFileName)) {
                System.out.println("<----------- ERR : file  " + this.workDir    + "/" + remoteFileName+ " does not exist, download failed!----------->");
                return null;
            } else {
                changeDir( this.workDir )  ;
                String[] fileNames = ftpClient.listNames();
                
                //設定傳輸二進位制檔案 
                setFileType(FTP.BINARY_FILE_TYPE);
                //獲得伺服器檔案 
                InputStream in = ftpClient.retrieveFileStream(remoteFileName);
                //輸出操作結果資訊 
                if (in != null) {
                    returnValue = new ByteArrayInputStream(IOUtils.toByteArray(in));
                    in.close();
                    System.out.println("<----------- INFO: download "+ this.workDir + "/" + remoteFileName+ " from ftp : succeed! ----------->");
                } else {
                    System.out.println("<----------- ERR : download "+ this.workDir + "/" + remoteFileName+ " from ftp : failed! ----------->");
                }
            }
            //關閉連線 
            closeConnect();
        } catch (Exception e) {
            e.printStackTrace();
            returnValue = null;
            //輸出操作結果資訊 
            System.out.println("<----------- ERR : download " +  this.workDir + "/" + remoteFileName+ " from ftp : failed! ----------->");
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    closeConnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return returnValue;
    }
    
    /**
     * 
     * @param remoteFilePath
     * @param remoteFileName
     * @param localFileName
     * @return
     * @throws IOException
     */
    public  boolean downloadFile(String remoteFilePath,
            String remoteFileName, String localFileName) throws IOException {
        boolean returnValue = false;
        //下載檔案 
        BufferedOutputStream buffOut = null;
        try {
            //連線ftp伺服器 
            connectToServer();
            File localFile = new File(localFileName.substring(0, localFileName
                    .lastIndexOf("/")));
            if (!localFile.exists()) {
                localFile.mkdirs();
            }
            if (!checkFileExist(remoteFilePath, remoteFileName)) {
                System.out.println("<----------- ERR : file  " + remoteFilePath    + "/" + remoteFileName+ " does not exist, download failed!----------->");
                return false;
            } else {
                changeDir( remoteFilePath )  ;
                String[] fileNames = ftpClient.listNames();
                
                //設定傳輸二進位制檔案 
                setFileType(FTP.BINARY_FILE_TYPE);
                //獲得伺服器檔案 
                buffOut = new BufferedOutputStream(new FileOutputStream(
                        localFileName));
                returnValue = ftpClient.retrieveFile(
                        remoteFileName, buffOut);
                //輸出操作結果資訊 
                if (returnValue) {
                    System.out.println("<----------- INFO: download "+ remoteFilePath + "/" + remoteFileName+ " from ftp : succeed! ----------->");
                } else {
                    System.out.println("<----------- ERR : download "+ remoteFilePath + "/" + remoteFileName+ " from ftp : failed! ----------->");
                }
            }
            //關閉連線 
            closeConnect();
        } catch (Exception e) {
            e.printStackTrace();
            returnValue = false;
            //輸出操作結果資訊 
            System.out.println("<----------- ERR : download " + remoteFilePath+ "/" + remoteFileName+ " from ftp : failed! ----------->");
        } finally {
            try {
                if (buffOut != null) {
                    buffOut.close();
                }
                if (ftpClient.isConnected()) {
                    closeConnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return returnValue;
    }
    
    /**
     * 
     * @param remoteFileNameList
     * @return
     * @throws IOException
     */
    public  List batchDownloadFile(
            List remoteFileNameList) throws IOException {
        InputStream resultIs = null ;
        List inputStreamList = null ;
        String remoteFileName = null ;
        
        if( remoteFileNameList == null ||remoteFileNameList.isEmpty() ) return null ;
            
        inputStreamList = new ArrayList() ;
        for( Iterator it = remoteFileNameList.iterator() ; it.hasNext() ; ) {
            remoteFileName = (String)it.next() ;
            resultIs = this.downloadFile(remoteFileName);
            if (resultIs != null ) {
                inputStreamList.add(resultIs) ;
            } 
        }
        return inputStreamList;
    }
    
    
    /**
     * 刪除伺服器上檔案
     * 
     * @param fileDir
     *            檔案路徑
     * @param fileName
     *            檔名稱
     * @throws IOException
     */
    public boolean delFile(String fileDir, String fileName) throws IOException {
        boolean returnValue = false;
        try {
            //連線ftp伺服器 
            connectToServer();
            //跳轉到指定的檔案目錄 
            if (fileDir != null) {
                if (fileDir.indexOf("/") != -1) {
                    int index = 0;
                    while ((index = fileDir.indexOf("/")) != -1) {
                        ftpClient.changeWorkingDirectory(fileDir.substring(0,
                                index));
                        fileDir = fileDir
                                .substring(index + 1, fileDir.length());
                    }
                    if (!fileDir.equals("")) {
                        ftpClient.changeWorkingDirectory(fileDir);
                    }
                } else {
                    ftpClient.changeWorkingDirectory(fileDir);
                }
            }
            //設定傳輸二進位制檔案 
            setFileType(FTP.BINARY_FILE_TYPE);
            //獲得伺服器檔案 
            returnValue = ftpClient.deleteFile(fileName);
            //關閉連線 
            closeConnect();
            //輸出操作結果資訊 
            if (returnValue) {
                System.out.println("<----------- INFO: delete " + fileDir + "/"
                        + fileName + " at ftp:succeed! ----------->");
            } else {
                System.out.println("<----------- ERR : delete " + fileDir + "/"
                        + fileName + " at ftp:failed! ----------->");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnValue = false;
            //輸出操作結果資訊 
            System.out.println("<----------- ERR : delete " + fileDir + "/"
                    + fileName + " at ftp:failed! ----------->");
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    closeConnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return returnValue;
    }

    /**
     * upload file to ftp 
     * @param uploadFile
     * @param fileName
     * @return
     * @throws IOException
     */
    public boolean uploadFile(String uploadFile , String fileName ) throws IOException{
        if(uploadFile == null || "".equals(uploadFile.trim())){
            System.out.println("<----------- ERR :  uploadFile:" + uploadFile
                    + " is null , upload failed! ----------->");
            return false ;
        }
        return this.uploadFile(new File(uploadFile) , fileName ) ;
    }
    
    
    /**
     * batch upload files 
     * @param uploadFileList
     * @return
     * @throws IOException
     */
    public boolean batchUploadFile(List uploadFileList ) throws IOException{
        if(uploadFileList == null || uploadFileList.isEmpty()){
            System.out.println("<----------- ERR :  batchUploadFile failed! because the file list is empty ! ----------->");
            return false ;
        }
        
        for( Iterator it = uploadFileList.iterator() ; it.hasNext() ;){
            File uploadFile = (File)it.next() ;
            if( !uploadFile(uploadFile , uploadFile.getName() ) ){
                System.out.println("<----------- ERR :  upload file【"+uploadFile.getName()+"】  failed! ----------->") ;
                return false ;
            }
        }
        return true ;
    }
    
    /**
     * upload file to ftp 
     * @param uploadFile
     * @param fileName
     * @return
     * @throws IOException
     */
    public  boolean uploadFile(File uploadFile, String fileName)
            throws IOException {
        if (!uploadFile.exists()) {
            System.out.println("<----------- ERR : an named " + fileName
                    + " not exist, upload failed! ----------->");
            return false;
        } 
        return this.uploadFile(new FileInputStream(uploadFile) , fileName ) ;
    }

    /**
     * upload file to ftp 
     * @param is
     * @param fileName
     * @return
     * @throws IOException
     */
    public boolean uploadFile(InputStream is , String fileName ) throws IOException {
        boolean returnValue = false;
        // 上傳檔案
        BufferedInputStream buffIn = null;
        try {
        
                // 建立連線
                connectToServer();
                // 設定傳輸二進位制檔案
                setFileType(FTP.BINARY_FILE_TYPE);
                // 獲得檔案
                buffIn = new BufferedInputStream(is);
                // 上傳檔案到ftp
                ftpClient.enterLocalPassiveMode();
                returnValue = ftpClient.storeFile(gbkToIso8859(this.workDir + "/"
                        + fileName), buffIn);
                // 輸出操作結果資訊
                if (returnValue) {
                    System.out.println("<----------- INFO: upload file  to ftp : succeed! ----------->");
                } else {
                    System.out.println("<----------- ERR : upload file  to ftp : failed! ----------->");
                }
                // 關閉連線
                closeConnect();
            
        } catch (Exception e) {
            e.printStackTrace();
            returnValue = false;
            System.out.println("<----------- ERR : upload file  to ftp : failed! ----------->");
        } finally {
            try {
                if (buffIn != null) {
                    buffIn.close();
                }
                if (ftpClient.isConnected()) {
                    closeConnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return returnValue ;
    }
    
    
      public boolean changeDirectory(String path) throws IOException {   
          return ftpClient.changeWorkingDirectory(path);   
        }   
        public boolean createDirectory(String pathName) throws IOException {   
            return ftpClient.makeDirectory(pathName);   
        }   
        public boolean removeDirectory(String path) throws IOException {   
            return ftpClient.removeDirectory(path);   
        } 
        // delete all subDirectory and files.   
        public boolean removeDirectory(String path, boolean isAll)   
                throws IOException {   
               
            if (!isAll) {   
                return removeDirectory(path);   
            }   
      
            FTPFile[] ftpFileArr = ftpClient.listFiles(path);   
            if (ftpFileArr == null || ftpFileArr.length == 0) {   
                return removeDirectory(path);   
            }   
            //    
            for (int i=ftpFileArr.length ; i>0 ; i-- ) {   
                FTPFile ftpFile = ftpFileArr[i-1] ; 
                String name = ftpFile.getName();   
                if (ftpFile.isDirectory()) {   
    System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]");                
                    removeDirectory(path + "/" + name, true);   
                } else if (ftpFile.isFile()) {   
    System.out.println("* [sF]Delete file ["+path + "/" + name+"]");                           
                    deleteFile(path + "/" + name);   
                }
//                else if (ftpFile.isSymbolicLink()) {   
//      
//                } else if (ftpFile.isUnknown()) {   
//      
//                }   
            }   
            return ftpClient.removeDirectory(path);   
        }   

        public boolean deleteFile(String pathName) throws IOException {   
            return ftpClient.deleteFile(pathName);   
        }   
        
        public List getFileList(String path) throws IOException {   
            FTPFile[] ftpFiles= ftpClient.listFiles(path);   
               
            List retList = new ArrayList();   
            if (ftpFiles == null || ftpFiles.length == 0) {   
                return retList;   
            }   
            for (int i=ftpFiles.length ; i>0 ; i-- ) {   
                FTPFile ftpFile = ftpFiles[i-1] ;
                  if (ftpFile.isFile()) {   
                        retList.add(ftpFile.getName());   
                    }   
            }
               
            return retList;   
        } 
        
        private void changeWordDir(String wd) throws IOException{
            if(wd != null && wd != ""){
                if(!ftpClient.changeWorkingDirectory(wd)){
                    ftpClient.makeDirectory(wd);
                    ftpClient.changeWorkingDirectory(wd);
                }
            }
        }
        
        /**
         * 上傳檔案到伺服器上
         * @param is 檔案流
         * @param filepath FTP伺服器上檔案路徑
         * @param filename 檔名稱
         * @return
         * @throws Exception
         */
        public boolean uploadFile(InputStream is,String filepath,String filename) throws Exception{
            if(!ftpClient.isConnected()){
                connectToServer();
            }
            changeWordDir(this.workDir);
            changeWordDir(filepath);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 
            ftpClient.enterLocalPassiveMode();
            boolean isSuccess = ftpClient.storeFile(filename, is);
            if(isSuccess){
                System.out.println("<-- INFO:upload "+workDir+"/"+filepath+"/"+filename+" from ftp: succeed -->");
            }else{
                System.out.println("<-- INFO:upload "+workDir+"/"+filepath+"/"+filename+" from ftp: failed -->");
            }
            is.close();
            closeConnect();
            return isSuccess;
        }
        
        /**
         * 從FTP伺服器上下載檔案
         * @param filepath FTP伺服器檔案路徑
         * @param filename 檔名稱
         * @param localPath 本機檔案路徑
         * @return
         * @throws IOException
         */
        public boolean downLoadFile(String filepath,String filename,String localPath) throws IOException{
            if(!ftpClient.isConnected()){
                connectToServer();
            }
            changeWordDir(this.workDir);
            changeWordDir(filepath);
            if(ftpClient.listNames(filename).length > 0){
                setFileType(FTP.BINARY_FILE_TYPE);
                File localFile = new File(localPath+"/"+filename);
                OutputStream os = new FileOutputStream(localFile);   
                boolean isSuccess = ftpClient.retrieveFile(filename, os);
                if(isSuccess){
                    System.out.println("<-- INFO:download "+workDir+"/"+filepath+"/"+filename+" from ftp: succeed -->");
                }else{
                    System.out.println("<-- INFO:download "+workDir+"/"+filepath+"/"+filename+" from ftp: failed -->");
                }
                os.close();
                closeConnect();
                return isSuccess;
            }else{
                System.out.println("<-- INFO:download "+workDir+"/"+filepath+"/"+filename+" from ftp: failed, file is not exist -->");
            }
            closeConnect();
            return false;
        }
        
        /**
         * 刪除FTP伺服器上的檔案
         * @param filepath 檔案路徑
         * @param filename 檔名稱
         * @throws IOException
         */
        public boolean deleteFile(String filepath,String filename) throws IOException{
            if(!ftpClient.isConnected()){
                connectToServer();
            }
            changeWordDir(this.workDir);
            changeWordDir(filepath);
            boolean isSuccess = false;
            if(ftpClient.listNames(filename).length > 0){
                isSuccess = ftpClient.deleteFile(filename);
                if(isSuccess){
                    System.out.println("<-- INFO:delete "+workDir+"/"+filepath+"/"+filename+" from ftp: succeed -->");
                }else{
                    System.out.println("<-- INFO:delete "+workDir+"/"+filepath+"/"+filename+" from ftp: failed -->");
                }
            }else{
                System.out.println("<-- INFO:delete "+workDir+"/"+filepath+"/"+filename+" from ftp: failed, file is not exist -->");
            }
            closeConnect();
            return isSuccess;
        }


    /**
     * download ftp .gz file as BufferedReader
     * @param remoteFileName
     * @return
     * @throws IOException
     */
    public  BufferedReader downloadGZFile(
            String remoteFileName, String filePath) throws IOException {
        BufferedReader returnValue = null;
        //下載檔案
        BufferedOutputStream buffOut = null;
        try {
            //連線ftp伺服器
            connectToServer();
            if (!checkFileExist(filePath, remoteFileName)) {
                System.out.println("<----------- ERR : file  " + filePath    + "/" + remoteFileName+ " does not exist, download failed!----------->");
                return null;
            } else {
                changeDir( filePath )  ;
                String[] fileNames = ftpClient.listNames();

                //設定傳輸二進位制檔案
                setFileType(FTP.BINARY_FILE_TYPE);
                //獲得伺服器檔案
                InputStream in = new GZIPInputStream(ftpClient.retrieveFileStream(remoteFileName));
                //輸出操作結果資訊
                if (in != null) {
                    returnValue = new BufferedReader(new InputStreamReader(in));
                    in.close();
                    System.out.println("<----------- INFO: download "+ filePath + "/" + remoteFileName+ " from ftp : succeed! ----------->");
                } else {
                    System.out.println("<----------- ERR : download "+ filePath + "/" + remoteFileName+ " from ftp : failed! ----------->");
                }
            }
            //關閉連線
            closeConnect();
        } catch (Exception e) {
            e.printStackTrace();
            returnValue = null;
            //輸出操作結果資訊
            System.out.println("<----------- ERR : download " +  filePath + "/" + remoteFileName+ " from ftp : failed! ----------->");
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    closeConnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return returnValue;
    }

    public String getWorkDir()
    {
        return this.workDir;
    }
}

 

reader.close();