2

我在 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;
            }
        }

    }

}
4

4 回答 4

3
String[] files = ftp.listnames();

如果需要的文件名包含在内,请查看文件...

于 2012-06-13T13:50:33.837 回答
2

假设ftpClient是 的一个实例org.apache.commons.net.ftp.FTPClient

public boolean fileExists(String fileName) throws IOException
{
    String[] files = ftpClient.listNames();

    return Arrays.asList(files).contains(fileName);
}
于 2015-06-15T19:08:46.110 回答
0

当客户端发送 RETR 并且服务器以错误代码 550 响应时,您可以非常确定该文件不存在或者您没有获取它的权限...由于 FTP 规范有点松散,您可能只是假设对于 550 - 559 范围内的任何错误,表示永久文件系统错误。

于 2011-09-14T15:21:01.637 回答
-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
于 2014-11-28T16:20:25.600 回答