Martin Prikr..
11
正如接受的答案所示,在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命令
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");
}
根据规范,FTP LIST命令仅接受文件夹的路径.
实际上,大多数FTP服务器都可以在LIST命令中接受文件掩码(确切的文件名也是一种掩码).但这超出了标准,并非所有FTP服务器都支持它(理所当然).
适用于任何FTP服务器的可移植代码必须在本地过滤文件:
String timestamp = ftpClient.getModificationTime(remotePath);
if (timestamp != null)
{
System.out.println("File " + remotePath + " exists");
}
else
{
System.out.println("File " + remotePath + " does not exists");
}
更高效的是使用LIST(mlistFile命令),如果服务器支持它:
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");
}
此方法可用于测试目录的存在.
如果服务器不支持MLST命令,则可以滥用 MLST(LIST命令):
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");
}
此方法不能用于测试目录的存在.