Reputation:
I have file like
LOG_EXPORT_TIME_STAMP_IMAGES-LOG1-T20130119_000817
LOG_EXPORT_TIME_STAMP_IMAGES-LOG1-T20130119_000818
LOG_EXPORT_TIME_STAMP_IMAGES-LOG1-T20130119_000819
at location "C:\temp"
I want to delete all files whatever starting with "LOG_EXPORT_TIME_STAMP_IMAGES"
.I have done some Google and got the code like
File file = new File("c:\\Temp\\LOG_EXPORT_TIME_STAMP_IMAGES-LOG1-T20130119_000817");
file.delete()
but what I observed I will have to pass full name of the file. Can I do it by passing the sub string of that file?
Upvotes: 3
Views: 4349
Reputation: 680
First list the files in the directory
File[] files = directory.listFiles();
Then iterate over the array and delete each file individually. This should give you more control to select files to delete.
Something on these lines:
File directory = new File("C:\temp");
File[] files = directory.listFiles();
for (File f : files)
{
if (f.getName().startsWith("LOG_EXPORT_TIME_STAMP_IMAGES"))
{
f.delete();
}
}
Upvotes: 6
Reputation: 652
Use a FilenameFilter to process filenames with known patterns.
In your case, try something like this:
File[] files = directory.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
if(name.startsWith(<your string here>)
{
return true;
}
return false;
}
});
Then iterate over the return file array to delete them.
Upvotes: 3
Reputation: 6089
You need the full file name, so you have to get a list of the files in the directory and iterate over them to determine which files to delete.
This post shows how to get the list of files and use it. It does deal with directories inside directories. list all files from directories and subdirectories in Java
Upvotes: 1