I have around 500 text files inside a directory with each with the same prefix in their filename, for example: dailyReport_
.
The latter part of the file is the date of the file. (For example 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 a 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? (e.g. 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 anything similar 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() ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With