0

give sample code for getting files of current date or req date in file chooser or file dialog? i need to filter files with date in file dialog?

karthik
  • 23
  • 1
  • 4

1 Answers1

1

First of all, I'm not sure if there is an existing File Filter using dates, so the best and quick solution for me was to implement my own Filter:

public class DateFileFilter extends FileFilter  
{    
     public boolean accept(File file)  
     {   
          GregorianCalendar date = new GregorianCalendar();//I get the today value  

          GregorianCalendar fileDate = new GregorianCalendar();  
          fileDate.setTimeInMillis(file.lastModified());//Here I get date info of the file 

          //Compare the current month and year  
          //with the month and yearthe file was  
          //last modified  
          return (((date.get(GregorianCalendar.MONTH) ==  
                fileDate.get(GregorianCalendar.MONTH)) &&  
               (date.get(GregorianCalendar.YEAR)  ==  
                fileDate.get(GregorianCalendar.YEAR))) ||  
               file.isDirectory());  
    }   

    public String getDescription()  
    {  
        return "This is my filter for dates (:";  
    }  
}  

Then you can add your filter to the JFileChooser:

JFileChooser jf = new JFileChooser();
jf.setFileFilter(/*HERE MY DATE FILTER*/);

For File Dialog, the process should be similar:

DateFileFilter filter = new DateFileFilter();
FileDialog dialog = new FileDialog(parent, "Choose File");   

        dialog.setFilenameFilter(filter);  

        dialog.show();  

        String selectedFile = dialog.getFile();   

But I think that you can also implement the "Filter" interface instead of make an "extends".

Hope it helps, best regards (:

Marcelo Tataje
  • 3,849
  • 1
  • 26
  • 51
  • Why the use of `GregorianCalendar`? You should be using `Calendar.getInstance()`, better yet, simply use `new Date()`. `Date` (and `Calendar`) have `before`, `after` and `compareTo` methods for comparing `Date` objects. It seems like a lot of extra work for little gain - IMHO – MadProgrammer Apr 03 '13 at 05:50
  • can you do the same for file dialog?? – karthik Apr 03 '13 at 05:52
  • I made an edit, hope it helps you. @MadProgrammer, thanks for your observation, I will consider it for refactoring my code. – Marcelo Tataje Apr 03 '13 at 06:00
  • its not filtering even when i mentioned as false in accept function in filtering – karthik Apr 03 '13 at 09:21