Java工具-檢驗ftp服務器的指定文件是否存在
阿新 • • 發佈:2018-08-29
str pac finall nec local 是否 inpu pen ole
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 */ publicstatic 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工具-檢驗ftp服務器的指定文件是否存在