14 Replies Latest reply: Apr 19, 2011 7:27 AM by EJP RSS

    How do i delete Older files from the directory before create a new file?


      How do i delete older files in a particular directory,

      the senorio is count the number of .txt files in a directory and delete the older files if file count is more than 10. (if i add 11th file the very first file has to be deleted)

      i have written the code to count the files and delete , but it is deleting all the files instead of older file
      public class ExtensionFilter implements FilenameFilter {
        private String extension;
        public ExtensionFilter( String extension ) {
          this.extension = extension;             
        public boolean accept(File dir, String name) {
          return (name.endsWith(extension));
      public class FileUtils{
        public static void main(String args[]) throws Exception {
          FileUtils.deleteFiles("c:/countfile/", ".txt");
        public static void deleteFiles( String directory, String extension ) {
          ExtensionFilter filter = new ExtensionFilter(extension);
          File dir = new File(directory);
          String[] list = dir.list(filter);
          File file;
          if (list.length == 0) return;
          for (int i = 0; i < list.length; i++) {
            //file = new File(directory + list);
      file = new File(directory, list[i]);
      if ((list[i]).length()>=10)
           System.out.print(file + " deleted : " + file.delete());

      Jamin Rosina