deleting files based on their dates

i am reading in a series of dates from a file,  i want to leave the ten newest dates.  I have code that will delete the oldest dates ten days from the current date,( courtesy of a previous post a few days ago).  however i dont want this, as files could be 3 weeks old but i will have to read from them so what i need to do is:

delete files by their date if and only if i dont need to read from that file i.e. that there is a file with a newer date than the file currently being checked.
and secondly i only want to leave the current latest 10 files again though there may not be 10 files and i want to match the above criteria.
 
here is my code.

static String processDir(File path)
      {
            Date todayDate = new Date();
            long today = todayDate.getTime();
            long closest = -1;
            Date closestDate = null;
            String file = "";
            String temp = "";
            int count = 0;
            File[] files = path.listFiles();
            for (int a = 0; a < files.length; a++)
            {
                  File currentFile = files[a];
            
                  if (currentFile.isFile() && currentFile.toString().endsWith(".txt") && currentFile.toString().substring(7,13).equals("upload"))
                  {      System.out.println(currentFile.toString().substring(7,13));
                        temp = currentFile.toString().substring(20, currentFile.toString().length() - 4);
                        try
                        {      //System.out.println(currentFile.toString().substring(7,13));
                              SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");  // example 25/10/2004, 14:30:19
                              Date d = df.parse(temp);
                              System.out.println(d);
                              Calendar cal = Calendar.getInstance();
                              cal.setTime(d);                                                // cal has date 25/10/2004, 14:30:19
                              cal.set(Calendar.MINUTE, 0);                    
                              cal.set(Calendar.SECOND, 0);        // now cal has 25/10/2004, 14:00:00

                              cal.add(Calendar.DAY_OF_WEEK , 11);  // now cal has 25/10/2004, 15:00:00
                              Date maxDate = cal.getTime();      // maxDate is 25/10/2004, 15:00:00      

                              //curclosest = java.lang.Math.min ( java.lang.Math.abs(today - d.getTime() ) );
                              System.out.println(maxDate);
                              long curclosest = (today - d.getTime());
                              
                              if(curclosest < 0 )
                              {
                                    curclosest = 0 - curclosest ;
                              }
                              if(closest == -1)
                              {
                                    closest = curclosest;
                                    closestDate = d;
                                    file = currentFile.toString();
                                    System.out.println(file);
                              }
                              else if(curclosest < closest )
                              {
                                    closest = curclosest;
                                    closestDate = d;  
                                    
                                    System.out.println(file);
                              }
                              
                              if(maxDate.before(todayDate))
                              {
                                    System.out.println(currentFile.toString() + " is being deleted");
                                    currentFile.delete();
                                    
                              }
                                    
                        }
                        catch(Exception e){}
                        //if(currentFile.ends
                        /* it's a directory, process its files and then
                         jump to the next file */
                        //processDir(currentFile);
                        //System.out.println(currentFile);
                        //System.out.println(currentFile);
                        //System.out.println(temp);
                        count++;
                        //continue;
                  }
            }System.out.println("The closest date was " + closestDate);
            System.out.println("total number of files is " + count);
            System.out.println("return filename " + file);
            return file;
      }

if anyone can help greatly appreciated, i know its only something small but i cant figure it.

LVL 1
pronaneAsked:
Who is Participating?
 
petmagdyCommented:
ok I got it, do this:

package com.pmy.tests;

import java.util.Collections;
import java.util.Date;
import java.util.Vector;

public class FileInfo implements Comparable {
      
      FileInfo(String fileName, Date fileDate)
      {
            this.fileName = fileName;
            this.fileDate = fileDate;
      }
      

      /**
       * @return Returns the fileDate.
       */
      public Date getFileDate() {
            return fileDate;
      }
      /**
       * @param fileDate The fileDate to set.
       */
      public void setFileDate(Date fileDate) {
            this.fileDate = fileDate;
      }
      /**
       * @return Returns the fileName.
       */
      public String getFileName() {
            return fileName;
      }
      /**
       * @param fileName The fileName to set.
       */
      public void setFileName(String fileName) {
            this.fileName = fileName;
      }
      String fileName;
      Date fileDate;
      
      
      /* (non-Javadoc)
       * @see java.lang.Comparable#compareTo(java.lang.Object)
       */
      public int compareTo(Object compared ) {
            FileInfo comparedFile = (FileInfo) compared;
            // TODO Auto-generated method stub
            return comparedFile.getFileDate().compareTo( getFileDate() );
      }

      public static void main(String[] args) {
            Vector files = new Vector();
            FileInfo file1 = new FileInfo("xyz", new Date());
            files.add(file1);
            FileInfo file2 = new FileInfo("wzy", new Date());
            files.add(file2);
            Collections.sort(files);
            
            //Keep the first 10 elements of the vector files and delete the rest
      }      

}

0
 
petmagdyCommented:
I don't sure I follow u, what I understand that u have some dates u want to eliminate all execpt the 10 newest Dates, right?
0
 
CEHJCommented:
If you'd paid attention to what i'd recommended in a previous question of yours, all you'd need to do now is tail a sorted List of LogDataRounder objects by ten ;-)
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
pronaneAuthor Commented:
sorry i tried i couldnt do it though!!!

i couldnt figure it out.  call me thick but there ye go!!!LOL

any suggestions on what ive done now?  

0
 
pronaneAuthor Commented:

petmagdy,  basically i create files based on their dates, so then i read in those files in the current directory, i want to read from the most recently dated file.

however i also want to leave the 10 newest log files and delete the rest.  however i dont know how to distinguish from the 10 most recent files basically,  currently if you see form the code, i have it set to 10 days, however if a file is older than 10 days it gets deleted.
0
 
pronaneAuthor Commented:
and the probelm lies, in if a file is older than 10 days but yet its the most recent file it will still get deleted.
0
 
sudhakar_koundinyaCommented:
check if  this helps u
mport java.util.Calendar;
import java.io.*;
 class FileDeleter {
   
    public static void main(String s[])
    {
        int diff=diffFromToday(new java.io.File("c:/dsd.txt"));
        if(diff>=10)
        {
            new java.io.File("c:/dsd.txt").delete();
        }
    }
    public static int diffFromToday(File f)
    {
             
        Calendar current=Calendar.getInstance();
        Calendar filetime=Calendar.getInstance();
        filetime.setTime(new java.util.Date(f.lastModified()));
        return(daysUntil(filetime,current));
    }
   
    public static int daysUntil(Calendar fromDate, Calendar toDate) {
        return daysSinceEpoch(toDate) - daysSinceEpoch(fromDate);
    }
   
    public static int daysSinceEpoch(Calendar day) {
        int year = day.get(Calendar.YEAR);
        int month = day.get(Calendar.MONTH);
        int daysThisYear = cumulDaysToMonth[month] + day.get(Calendar.DAY_OF_MONTH) - 1;
        if ((month > 1) && isLeapYear(year)) {
            daysThisYear++;
        }

        return daysToYear(year) + daysThisYear;
    }
   
    public static boolean isLeapYear(int year) {
        return (year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0));
    }
   
    static int daysToYear(int year) {
        return (365 * year) + numLeapsToYear(year);        
    }

    static int numLeapsToYear(int year) {
        int num4y = (year - 1) / 4;
        int num100y = (year - 1) / 100;
        int num400y = (year - 1) / 400;
        return num4y - num100y + num400y;
    }
   
    private static final int[] cumulDaysToMonth = { 0, 31, 59, 90, 120, 151,
            181, 212, 243, 273, 304, 334 };
}


0
 
petmagdyCommented:
to explain this code in my last comment I created a class that holds the Filename and its Date,

So u will create a Vector (files), read from the directory the files and fill in the FileInfo Class and put it into this vector, after u finish call:

Collections.sort(files), they will be sorted descending based on their date, so u keep the first 10 elements in the vector and delete the rest
0
 
pronaneAuthor Commented:
ok i have added it like you said, and i just wanted to print out the files once they have been sorted.  this is what ive done, but all that is printed is memory addresses:



                 Collections.sort(files);
       for(int i = 0; i < files.size();i++)
       System.out.println(files.get(i).toString());

by the way the filenames come in like this

"change20041027.txt"
"change20041029.txt"

can this class differentiate between these?
             
0
 
petmagdyCommented:
to file info add this method:

public String toString()
{
  return fileName;
}
0
 
pronaneAuthor Commented:
ya that worked, where should i call the compareto method

and does it matter what the name fo the filenames are, because i printed it out and the files came back in the same order as they were put in even after running the line
collections.sort

thanks for the help
0
 
pronaneAuthor Commented:

is it possible to put in this line
 FileInfo file1 = new FileInfo("bulk_change_stats_20041027.txt", new Date());

 something like new FileInfo("bulk_change_stats_20041027.txt", file1.lastModified());
0
 
petmagdyCommented:
u don't call compareTo, the collections.sort will

u can construct fileInfo with any thing as u want as long as compatible datatypes

new FileInfo("anyString", any Date)
0
 
petmagdyCommented:
u can also modify toString to be like this:

public String toString()
{
  return "FileName: " + fileName + " FileDate: " + fileDate.toString();
}
0
 
pronaneAuthor Commented:
can construct fileInfo with any thing as u want as long as compatible datatypes

"

no what i mean though is for the given file that is being passed in, can you get the lasmodified date for
that to pass it through, as that is how i will be able to sort the dates.  Because its not sorting
the files by date with the above code, it just prints out the files as they were read in.  
Do you follow me?
0
 
petmagdyCommented:
yes construct fileinfo based on the filename and file last modified date, that was the purpose from the begining
0
 
pronaneAuthor Commented:

/*ya thats the problem i was on about, like anything ive tried to put in there wont work.
how do i pass in the date for the current file im trying to pass in as the string?
0
 
petmagdyCommented:
ok, suppose:
File myfile = new File("c:\temp\myfile.doc");

Date lastModified = new Date( myfile.lastModified() );

FileInfo file1 = new FileInfo( "c:\temp\myfile.doc", lastModified );
0
 
pronaneAuthor Commented:
ya i did that already, i was just hoping there was another quicker way.

thanks for all the help.

it sorts them by the oldest dates though, not the newest, so its keeping the oldest files to hte top, i didnt want thaat, i wanted to delete the oldest files so i wanted it to put the newest files first, so that i can delete anything after the 10 most newest files.
0
 
petmagdyCommented:
ok opposite the logic in compare to be like this:

    public int compareTo(Object compared ) {
          FileInfo comparedFile = (FileInfo) compared;
          // TODO Auto-generated method stub
          return getFileDate().compareTo( comparedFile.getFileDate() );
     }

0
 
pronaneAuthor Commented:
ok ive tested this with a few different files and dates these files have been modified, however, it doesnt work correctly.

With an example of 3 files ( as its the easiet to explain )it appears that the oldest modified file ends up in the middle, the newest modified at the front, and the second most recent modified filei at the end,  where it should be that the oldest modified ends up at the end.

i tried it with the other way around as well, that they were being descended by oldest date, and its the sane, the oldest file ends up in the middle as well
0
 
petmagdyCommented:
please post the complete sample of getting 3 files and sort them
0
 
pronaneAuthor Commented:
no i think it may have been somthing i did, it appears fine now.  thanks again for all the help, very much appreciated.
0
 
petmagdyCommented:
welcome :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.