使用Java删除具有相同前缀字符串的文件 [英] Delete Files with same Prefix String using Java

查看:1652
本文介绍了使用Java删除具有相同前缀字符串的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在目录中有大约500个文本文件,其文件名中包含相同的前缀,如 dailyReport _



文件的后半部分是文件的日期。 (例如。 dailyReport_08262011.txt dailyReport_08232011.txt



我想使用Java程序删除这些文件(我可以使用shell脚本并在crontab中添加一个作业,但该应用程序应由外行使用)。



我可以使用类似的东西删除一个文件

 试试{
文件f =新文件( dailyReport_08232011.txt);
f.delete();
}
catch(例外e){
System.out.println(e);
}

但是我可以删除具有特定前缀的文件(例如: dailyReport08 第8个月)我可以使用 rm -rf dailyReport08 * .txt 轻松地在shell脚本中执行此操作。



但是文件f =新文件(dailyReport_08 * .txt); 在Java中不起作用(如预期的那样)。 / p>

现在,在Java 中没有运行循环可以搜索目录中的文件吗?



我可以使用类似于shell脚本中使用的 * 的特殊字符来实现这一点吗?

解决方案

不,你不能。 Java是一种相当低级的语言 - 与shell脚本相比 - 所以这样的事情必须更加明确地完成。您应该使用folder.listFiles(FilenameFilter)搜索具有所需掩码的文件,并迭代返回的数组,删除每个条目。像这样:

  final文件夹= ... 
final File [] files = folder.listFiles(new FilenameFilter (){
@Override
public boolean accept(final file dir,
final String name){
return name.matches(dailyReport_08。* \\.txt );
}
});
for(final file file:files){
if(!file.delete()){
System.err.println(无法删除+ file.getAbsolutePath()) ;
}
}


I have around 500 text files inside a directory with a same prefix in their filename say dailyReport_.

The latter part of the file is the date of the file. (For eg. dailyReport_08262011.txt, dailyReport_08232011.txt)

I want to delete these files using a Java procedure (I could go for a shell script and add it a job in the crontab but the application is meant to used by laymen).

I can delete one single file using something like this

        try{
          File f=new File("dailyReport_08232011.txt");
          f.delete();
        }
        catch(Exception e){ 
                System.out.println(e);
        }

but can I delete the files having a certain prefix (eg: dailyReport08 for the 8th month ) I could easily do that in shell script by using rm -rf dailyReport08*.txt .

But File f=new File("dailyReport_08*.txt"); doesnt work in Java (as expected).

Now is any thing as such possible in Java without running a loop that searches the directory for files?

Can I achieve this using some special characters similar to * used in shell script?

解决方案

No, you can't. Java is rather low-level language -- comparing with shell-script -- so things like this must be done more explicetly. You should search for files with required mask with folder.listFiles(FilenameFilter), and iterate through returned array deleting each entry. Like this:

final File folder = ...
final File[] files = folder.listFiles( new FilenameFilter() {
    @Override
    public boolean accept( final File dir,
                           final String name ) {
        return name.matches( "dailyReport_08.*\\.txt" );
    }
} );
for ( final File file : files ) {
    if ( !file.delete() ) {
        System.err.println( "Can't remove " + file.getAbsolutePath() );
    }
}

这篇关于使用Java删除具有相同前缀字符串的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆