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

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

}

此方法不能用于测试目录的存在.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值