有没有检查文件是否存在一个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");
}
更有效的是使用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
命令,你可以滥用 getModificationTime
( MDTM
命令):
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