1. 程式人生 > >FTP伺服器檔案存在性判斷

FTP伺服器檔案存在性判斷

在實際使用FTP檔案伺服器的過程中,經常需要遠端下載解析檔案。為提高效率,需要判斷檔案存在與否,有選擇的進行解析。

這裡對專案中的一個小片段進行備份,方便以後總結學習。


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

      /**
 	 * 方法描述:檢驗指定路徑的檔案是否存在ftp伺服器中
 	 * @author guoxk
 	 * @createTime 2017年5月11日 上午11:26:44
 	 *
 	 * @param filePath 指定絕對路徑的檔案 127.0.0.1:21/TEST/20161010/test_20161010.zip
 	 * @param user     ftp伺服器登陸使用者名稱 username
 	 * @param passward ftp伺服器登陸密碼 password
 	 * @param ip       ftp的IP地址 127.0.0.1
 	 * @param port     ftp的埠號 21
 	 * @return 存在返回true,不存在返回false
 	 */
	  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.enterLocalPassiveMode(); //開啟本地被動模式--Linux,windowns開啟主動enterLocalActiveMode
			
                        // 設定檔案型別為二進位制,與ASCII有區別
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			// 設定編碼格式
			ftp.setControlEncoding("GBK");

			// 提取絕對地址的目錄以及檔名
			filePath = filePath.replace(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) {
			//logger.error(e.getMessage());
		} finally {
			if (ftp != null) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					//logger.error(e.getMessage());
				}
			}
		}
		return false;
	}