Mic*_*che 15 java ftp apache-commons-net
有没有一种有效的方法来检查FTP服务器上是否存在文件?我正在使用Apache Commons Net.我知道我可以使用listNames方法FTPClient来获取特定目录中的所有文件,然后我可以查看此列表以检查给定文件是否存在,但我不认为它是有效的,尤其是当服务器包含大量文件.
Mar*_*ryl 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");
}
Run Code Online (Sandbox Code Playgroud)
但它实际上违反了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");
}
Run Code Online (Sandbox Code Playgroud)
根据规范,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");
}
Run Code Online (Sandbox Code Playgroud)
更高效的是使用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");
}
Run Code Online (Sandbox Code Playgroud)
此方法可用于测试目录的存在.
如果服务器不支持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");
}
Run Code Online (Sandbox Code Playgroud)
此方法不能用于测试目录的存在.