檢驗指定路徑的文件是否存在ftp服務器中


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

/**
*  檢驗指定路徑的文件是否存在ftp服務器中
* @param filePath--指定絕對路徑的文件
* @param user--ftp服務器登陸用戶名
* @param passward--ftp服務器登陸密碼
* @param ip--ftp的IP地址
* @param port--ftp的端口號
* @return
*/

public static boolean isFTPFileExist(String filePath,String user,String passward,String ip,int port){
        FTPClient ftp = new FTPClient();
        try {
    // 連接ftp服務器
            ftp.connect(ip, port);
            // 登陸    
            ftp.login(user, passward);
           // 檢驗登陸操作的返回碼是否正確
            if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())){
                ftp.disconnect();
                return false;
            }
            
            ftp.enterLocalActiveMode();
            // 設置文件類型為二進制,與ASCII有區別
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            // 設置編碼格式
            ftp.setControlEncoding("GBK");
            
            // 提取絕對地址的目錄以及文件名
            filePath = filePath.replace("ftp://"+ip+":"+port+"/", "");
            String dir = filePath.substring(0, filePath.lastIndexOf("/"));
            String file = filePath.substring(filePath.lastIndexOf("/")+1);
            
            // 進入文件所在目錄,注意編碼格式,以能夠正確識別中文目錄
            ftp.changeWorkingDirectory(new String(dir.getBytes("GBK"),FTP.DEFAULT_CONTROL_ENCODING));

            // 檢驗文件是否存在
            InputStream is = ftp.retrieveFileStream(new String(file.getBytes("GBK"),FTP.DEFAULT_CONTROL_ENCODING));
            if(is == null || ftp.getReplyCode() == FTPReply.FILE_UNAVAILABLE){
                return false;
            }
            
            if(is != null){
                is.close();
                ftp.completePendingCommand();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(ftp != null){
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM