java 文件前缀,使用Java删除具有相同前缀字符串的文件

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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值