Home > Mobile >  Filter out files older than a week JFileChooser - Java
Filter out files older than a week JFileChooser - Java

Time:06-28

I'm quite new to programming, in fact I just finished school and just started in an IT Department until I start University in some months.

However, I was given the task to make a program that copies files from one folder to another, where the user doesn't have much impact besides of choosing the files. I got everything to work, but now I was asked to implement it so that only Files from the last week are presented in the FileChooser.

Personally, I assume that I somehow (probs with an Array?) have to check all Files for their date and compare it to current date. Which I guess I would do with a for-loop.

But I honestly have no Idea how to approach it. I think the main problem is that I don't know how to fetch the files from the directory in advance and send them through the loop.

Any help would be appreciated. If you need more information, let me know.

Thank you in advance.

CodePudding user response:

You just need to create a custom Filter class for your JFileChooser to do what you want. Normally you would apply one or more filters to your file chooser instance by providing a file name extension and a file description (there are other variants of this however). By creating you own Filter class, you can make it display whatever files you like and under whatever circumstance you want.

Below is an example of a custom JFileChooser File Filter. With it in place you can declare a filter that will only display whatever files with whatever file extensions that have a file date from the current date to whatever provided days prior (a date range). Here is the Custom JFileChooser Filter class:

public class MyFileChooserFileFilter extends javax.swing.filechooser.FileFilter {

    private String extension;
    private String description;
    private int daysBefore = 0;

    public MyFileChooserFileFilter(String extension, String description) {
        this.extension = extension;
        this.description = description;
    }
    
    public MyFileChooserFileFilter(String extension, String description, int daysBefore) {
        this.extension = extension;
        this.description = description;
        this.daysBefore = daysBefore;
    }
    
    public MyFileChooserFileFilter(int daysBefore) {
        this.daysBefore = daysBefore;
    }

    @Override
    public boolean accept(File file) {
        if (file.isDirectory()) {
            return true;
        }
        if (this.daysBefore > 0) {
            // Get the file's date and convert it to LocalDate
            java.time.LocalDate fileDate = java.time.Instant.ofEpochMilli(file.lastModified())
                                        .atZone(java.time.ZoneId.systemDefault()).toLocalDate();
            
            // Get current Date as LocalDate. This will be considered the End Date.
            java.time.LocalDate fileEndDate = java.time.LocalDate.now();
            /* Get Date from the supplied number of days ago as LocalDate. 
               This will be sonsidered the Start Date.                */
            java.time.LocalDate fileStartDate = fileEndDate.minusDays(this.daysBefore);
            
            /* Chaeck if the file's date is in range. If it isn't then don't 
               display it within the JDateChooser. If it is then display it.  */
            if ((fileDate.isBefore(fileEndDate) || fileDate.isEqual(fileEndDate)) && 
                    (fileDate.isEqual(fileStartDate) || fileDate.isAfter(fileStartDate)) &&
                    (file.getName().endsWith(extension))) {
                
                /* If the file name has our desired file name extension and the
                   file date in within our date range then return true to indicate 
                   the file is acceptable and can be displayed.                */
                return true;
            }
            /* Otherwise it is not acceptable for this current filter instance 
               and therefore return false so as not to display the file name.*/
            else { 
                return false; 
            }
        }
        // For other filter type instances.
        return file.getName().endsWith(extension);
    }

    @Override
    public String getDescription() {
        return description   String.format(" (*%s)", extension);
    }
}

And here is how you might use this class with your JFileChooser:

javax.swing.JFileChooser fileChooser = new javax.swing.JFileChooser();
fileChooser.setCurrentDirectory(new File(""));
fileChooser.setFileSelectionMode(javax.swing.JFileChooser.FILES_ONLY);
    
javax.swing.filechooser.FileFilter txtFilter = new MyFileChooserFileFilter(".txt", "Text Files From Last 6 Days", 6);
javax.swing.filechooser.FileFilter allTxtFilter = new MyFileChooserFileFilter(".txt", "All Text Files");
javax.swing.filechooser.FileFilter docFilter = new MyFileChooserFileFilter(".docx", "Microsoft Word Documents");
javax.swing.filechooser.FileFilter pdfFilter = new MyFileChooserFileFilter(".pdf", "PDF Documents");
javax.swing.filechooser.FileFilter xlsFilter = new MyFileChooserFileFilter(".xlsx", "Microsoft Excel Documents");
fileChooser.addChoosableFileFilter(txtFilter);
fileChooser.addChoosableFileFilter(allTxtFilter);
fileChooser.addChoosableFileFilter(docFilter);
fileChooser.addChoosableFileFilter(pdfFilter);
fileChooser.addChoosableFileFilter(xlsFilter);

fileChooser.setAcceptAllFileFilterUsed(true);

int result = fileChooser.showOpenDialog(this);

if (result == javax.swing.JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    System.out.println("Selected file: "   selectedFile.getAbsolutePath());
}
  • Related