java中如何检验ftp服务器中指定文件是否存在

互联网 19-11-27

检验思路:

首先需要连接“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服务器中指定文件是否存在的详细内容,更多内容请关注技术你好其它相关文章!

来源链接:
免责声明:
1.资讯内容不构成投资建议,投资者应独立决策并自行承担风险
2.本文版权归属原作所有,仅代表作者本人观点,不代表本站的观点或立场
标签: 存在
上一篇:php获取远程图片并下载保存到本地的方法分析 下一篇:java判断指定元素是否包含数组中的方法介绍

相关资讯