前提:FTPClient能登录成功,changeWorkingDirectory返回true;文件名无误。
代码:
/**
* @Author WangChangDian
* @Description //TODO 判断文件是否存在
* @Date 18:18 2020/2/1
* @param filePath--指定绝对路径的文件
* @return
*/
public static boolean isFTPFileExist(String filePath){
/* 测试数据
* url:服务器ip
* port : 21
* ftpUsername:root
* ftpPassword :12345
* filePath:aa/bb/cc/test.jpg
**/
FTPClient ftp = new FTPClient();
try {
// 连接ftp服务器
ftp.connect(url, port);
// 登陆
ftp.login(ftpUsername, ftpPassword);
// 检验登陆操作的返回码是否正确
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://"+url+":"+port+"/", "");
String dir = filePath.substring(0, filePath.lastIndexOf("/"));
String file = filePath.substring(filePath.lastIndexOf("/")+1);
// 进入文件所在目录,注意编码格式,以能够正确识别中文目录
boolean cdStatus = 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;
}
如果 “is”为null,请检查服务器根目录权限配置,务必提供读取权限,我直接给根目录及其所有子目录 最高权限,如图:
再次运行代码,发现“is”有值,说明读取到文件了。