如何删除FTP目录中的所有txt文件?

我的应用程序将 txt 文件存储在 FTP 服务器上,该服务器也托管在网络服务上。


在我托管 txt 文件的目录中,我可以找到其他 txt 文件。每次存储新文件时,我都想删除当前目录中的所有文件。


实际上我正在尝试使用以下命令:


FTPClient ftpClient = new FTPClient();

ftpClient.connect(siteFTP);

if (ftpClient.login(usrFTP, pswFTP)) {

  ftpClient.enterLocalPassiveMode();          

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

  if (remoteFiles.length > 0) {

    ftpClient.deleteFile("/prenotazioni/*.txt");

  }

}

但即使该目录中有 txt 文件,FTP 响应也是:


> DELE /prenotazioni/*.txt

> 550 File not found


慕慕森
浏览 180回答 2
2回答

尚方宝剑之说

使用*是不行的。在您获得声明目录中的文件列表后,您必须迭代它并使用deleteFile(String pathname)(同时检查文件名endsWith(".txt"))一个一个地删除文件。各有FTPFile办法getName()。您应该构建完整路径,以便FTPClient知道要删除的文件。我相信它会是这样的:ftpClient.deleteFile("/prenotazioni/" + remoteFiles[i].getName());

白衣非少年

完整方法:&nbsp; &nbsp; public static void deleteFilesInFolderFtp(String dirPath, FTPClient ftpClient) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; // use local passive mode to pass firewall&nbsp; &nbsp; &nbsp; &nbsp; ftpClient.enterLocalPassiveMode();&nbsp; &nbsp; &nbsp; &nbsp; FTPFile[] remoteFiles = ftpClient.listFiles("/" + dirPath);&nbsp; &nbsp; &nbsp; &nbsp; if (remoteFiles.length > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < remoteFiles.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ftpClient.deleteFile("/" + dirPath + "/" + remoteFiles[i].getName());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } catch (IOException ex) {&nbsp; &nbsp; &nbsp; &nbsp; ex.printStackTrace();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java