首頁  >  文章  >  Java  >  java中如何檢驗ftp伺服器中指定檔案是否存在

java中如何檢驗ftp伺服器中指定檔案是否存在

王林
王林原創
2019-11-27 10:49:053725瀏覽

java中如何檢驗ftp伺服器中指定檔案是否存在

檢驗想法:

首先需要連接「ftp」伺服器,然後設定檔案類型為二進制,並設定編碼格式,接著提取絕對位址的目錄及檔名,最後檢驗指定文件是否存在即可。

推薦java相關影片教學:java線上學習

範例程式碼如下:

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

推薦java相關文章教學: java程式入門

以上是java中如何檢驗ftp伺服器中指定檔案是否存在的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn