检查 FTP 服务器上的文件是否存在

问题描述 投票:0回答:4

有没有一种有效的方法来检查 FTP 服务器上文件是否存在?我正在使用 Apache Commons Net。我知道我可以使用

listNames
FTPClient
方法来获取特定目录中的所有文件,然后我可以遍历此列表来检查给定文件是否存在,但我认为它效率不高,尤其是在服务器包含很多文件。

java ftp apache-commons-net
4个回答
28
投票

listFiles(String pathName)
对于单个文件应该可以正常工作。


18
投票

listFiles
(或
mlistDir
)调用中使用文件的完整路径,正如接受的答案所示,确实应该有效:

String remotePath = "/remote/path/file.txt";
FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);
if (remoteFiles.length > 0)
{
    System.out.println("File " + remoteFiles[0].getName() + " exists");
}
else
{
    System.out.println("File " + remotePath + " does not exists");
}

RFC 959第4.1.3节中关于

LIST
命令的部分说:

如果路径名指定一个文件,那么服务器应该发送该文件的当前信息。

虽然如果你要检查很多文件,这将是相当低效的。

LIST
命令的使用实际上涉及多个命令,等待它们的响应,主要是打开数据连接。打开新的 TCP/IP 连接是一项成本高昂的操作,在使用加密时更是如此(如今这是必须的)。

此外,

LIST
命令对于测试文件夹是否存在更加无效,因为它会导致传输完整的文件夹内容。


更高效的是使用

mlistFile
MLST
命令),如果服务器支持的话:

String remotePath = "/remote/path/file.txt";
FTPFile remoteFile = ftpClient.mlistFile(remotePath);
if (remoteFile != null)
{
    System.out.println("File " + remoteFile.getName() + " exists");
}
else
{
    System.out.println("File " + remotePath + " does not exists");
}

此方法可以用于测试目录是否存在。

MLST
命令不使用单独的连接(与
LIST
相反)。


如果服务器不支持

MLST
命令,您可以滥用
getModificationTime
MDTM
命令)或
getSize
SIZE
命令):

String timestamp = ftpClient.getModificationTime(remotePath);
if (timestamp != null)
{
    System.out.println("File " + remotePath + " exists");
}
else
{
    System.out.println("File " + remotePath + " does not exists");
}

此方法不能用于测试目录是否存在。


2
投票

接受的答案对我不起作用。

代码不起作用:

String remotePath = "/remote/path/file.txt";
FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);

相反,这对我有用:

ftpClient.changeWorkingDirectory("/remote/path");
FTPFile[] remoteFiles = ftpClient.listFiles("file.txt");

-1
投票
public boolean isDirectory(String dstPath) throws IOException {
    return ftpsClient.changeWorkingDirectory(dstPath);
}

public boolean exists(String dstPath) throws IOException {
    if (isDirectory(dstPath)) {
        return true;
    }
    FTPFile[] remoteFiles = ftpsClient.listFiles(dstPath);
    return remoteFiles != null && remoteFiles.length > 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.