简体   繁体   English

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

[英]How to delete all txt files inside an FTP directory?

My app stores txt files on a FTP server which are also hosted on webservice.我的应用程序将 txt 文件存储在 FTP 服务器上,该服务器也托管在网络服务上。

In the directory where I host txt files I can find other txt files.在我托管 txt 文件的目录中,我可以找到其他 txt 文件。 I would like to delete all files in current directory every time when I store the new ones.每次存储新文件时,我都想删除当前目录中的所有文件。

Actually i was trying to use the following command:实际上我正在尝试使用以下命令:

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

But even if there was txt files in that directory, FTP respose is:但即使该目录中有 txt 文件,FTP 响应也是:

> DELE /prenotazioni/*.txt
> 550 File not found

Using * won't work.使用*将不起作用。 After You get list of files in declared directory, You must iterate it and delete files one by one by using deleteFile(String pathname) (also checking if file name endsWith(".txt") ).在您获得声明目录中的文件列表后,您必须对其进行迭代并使用deleteFile(String pathname)一一删除文件(还检查文件名是否endsWith(".txt") )。

Every FTPFile has method getName() .每个FTPFile都有方法getName() You should construct full path so FTPClient will know what file to delete.您应该构建完整路径,以便FTPClient知道要删除的文件。 I believe it would be something like:我相信它会是这样的:

ftpClient.deleteFile("/prenotazioni/" + remoteFiles[i].getName());

full method:完整方法:

    public static void deleteFilesInFolderFtp(String dirPath, FTPClient ftpClient) {
    try {
        // use local passive mode to pass firewall
        ftpClient.enterLocalPassiveMode();
        FTPFile[] remoteFiles = ftpClient.listFiles("/" + dirPath);
        if (remoteFiles.length > 0) {
            for (int i = 0; i < remoteFiles.length; i++) {
                ftpClient.deleteFile("/" + dirPath + "/" + remoteFiles[i].getName());
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM