3

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?

  • be sure to check if the directory is really a directory and that each of the files you get back is really a file. that's why I suggested looking at the recursive directory lister. – Peter Wooster Jan 19 '13 at 08:54

3 Answers3

5

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();
    }
}
Taky
  • 5,284
  • 1
  • 20
  • 29
pratikch
  • 670
  • 5
  • 19
3

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.

Shyamal Pandya
  • 532
  • 3
  • 16
1

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

Community
  • 1
  • 1
Peter Wooster
  • 6,009
  • 2
  • 27
  • 39