我在android上使用apache FTPClient。我想从ftp服务器下载文件。但我想在下载前检查服务器上是否存在。我怎么检查这个?
谢谢,
我的代码:
public static boolean getFile(String serverName, String userName,
String password, String serverFilePath, String localFilePath)
throws Exception {
FTPClient ftp = new FTPClient();
try {
ftp.connect(serverName);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return false;
}
} catch (IOException e) {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
throw e;
}
}
throw e;
} catch (Exception e) {
throw e;
}
try {
if (!ftp.login(userName, password)) {
ftp.logout();
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
OutputStream output;
output = new FileOutputStream(localFilePath);
ftp.retrieveFile(serverFilePath, output);
output.close();
ftp.noop(); // check that control connection is working OK
ftp.logout();
return true;
} catch (FTPConnectionClosedException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
throw f;
}
}
}
}
答案 0 :(得分:2)
String[] files = ftp.listnames();
如果需要文件名包括,请查看文件。
答案 1 :(得分:1)
假设ftpClient
是org.apache.commons.net.ftp.FTPClient
的实例:
public boolean fileExists(String fileName) throws IOException
{
String[] files = ftpClient.listNames();
return Arrays.asList(files).contains(fileName);
}
答案 2 :(得分:0)
当客户端发送RETR并且服务器响应错误代码550时,您可以非常确定该文件不存在或者您没有获取它的权限...由于FTP规范有点松散您可能只是假设550 - 559范围内的任何错误,这表示永久文件系统错误。
答案 3 :(得分:-2)
InputStream inputStream = ftpClient.retrieveFileStream(filePath);
if (inputStream == null || ftpClient.getReplyCode() == 550) {
// it means that file doesn't exist.
}
or
FTPFile[] mFileArray = ftp.listFiles();
// you can check if array contains needed file