Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

deleting files based on their dates

Posted on 2004-10-29
24
Medium Priority
?
205 Views
Last Modified: 2010-03-31
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.

0
Comment
Question by:pronane
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 11
  • +1
24 Comments
 
LVL 13

Expert Comment

by:petmagdy
ID: 12447614
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 12447708
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
 
LVL 1

Author Comment

by:pronane
ID: 12447802
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:pronane
ID: 12447826

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
 
LVL 1

Author Comment

by:pronane
ID: 12447839
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12447947
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
 
LVL 13

Accepted Solution

by:
petmagdy earned 200 total points
ID: 12447969
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
 
LVL 13

Expert Comment

by:petmagdy
ID: 12448017
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
 
LVL 1

Author Comment

by:pronane
ID: 12461417
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
 
LVL 13

Expert Comment

by:petmagdy
ID: 12461489
to file info add this method:

public String toString()
{
  return fileName;
}
0
 
LVL 1

Author Comment

by:pronane
ID: 12461515
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
 
LVL 1

Author Comment

by:pronane
ID: 12461524

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
 
LVL 13

Expert Comment

by:petmagdy
ID: 12461552
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
 
LVL 13

Expert Comment

by:petmagdy
ID: 12461566
u can also modify toString to be like this:

public String toString()
{
  return "FileName: " + fileName + " FileDate: " + fileDate.toString();
}
0
 
LVL 1

Author Comment

by:pronane
ID: 12461593
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
 
LVL 13

Expert Comment

by:petmagdy
ID: 12461613
yes construct fileinfo based on the filename and file last modified date, that was the purpose from the begining
0
 
LVL 1

Author Comment

by:pronane
ID: 12461655

/*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
 
LVL 13

Expert Comment

by:petmagdy
ID: 12461675
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
 
LVL 1

Author Comment

by:pronane
ID: 12461706
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
 
LVL 13

Expert Comment

by:petmagdy
ID: 12461717
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
 
LVL 1

Author Comment

by:pronane
ID: 12461805
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
 
LVL 13

Expert Comment

by:petmagdy
ID: 12461835
please post the complete sample of getting 3 files and sort them
0
 
LVL 1

Author Comment

by:pronane
ID: 12461938
no i think it may have been somthing i did, it appears fine now.  thanks again for all the help, very much appreciated.
0
 
LVL 13

Expert Comment

by:petmagdy
ID: 12461945
welcome :)
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question