FTP服务器上检查文件是否存在FTP服务器上检查文件是否存在(Checking file exist

2019-05-13 21:37发布

有没有检查文件是否存在一个FTP服务器上的有效途径? 我使用的Apache共享网络。 我知道,我可以使用listNames的方法FTPClient获得在特定目录下的所有文件,然后我就可以去在这个清单来检查,如果给定的文件存在,但特别是当服务器包含一个我不认为这是有效的很多文件。

Answer 1:

listFiles(String pathName)应该只是罚款单个文件。



Answer 2:

使用完整路径的文件listFiles (或mlistDir )调用,作为公认的答案显示,的确会为众多的FTP服务器的工作:

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");
}

但是,因为它映射到一个FTP命令它实际上违反了FTP规范

LIST /remote/path/file.txt

根据本说明书中,FTP LIST命令接受仅一个文件夹的路径。

事实上, 大多数FTP服务器,可以接受在一个文件掩码LIST命令 (和确切的文件名是一种面具的太)。 但是,这是超出标准,而不是所有的FTP服务器都支持它(理所当然)。


任何FTP服务器上工作的便携式代码必须在本地过滤文件:

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

Optional<FTPFile> remoteFile =
    Arrays.stream(remoteFiles).filter(
        (FTPFile remoteFile2) -> remoteFile2.getName().equals("file.txt")).findFirst();
if (remoteFile.isPresent())
{
    System.out.println("File " + remoteFile.get().getName() + " exists");
}
else
{
    System.out.println("File does not exists");
}

更有效的是使用mlistFileMLST如果服务器支持它命令),:

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命令,你可以滥用 getModificationTimeMDTM命令):

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

此方法不能被用来测试一个目录的存在。



文章来源: Checking file existence on FTP server