How to get all files of particular date modified f

2019-06-14 19:54发布

问题:

Blockquote

I want to filter the files according to its date and time ,but i couldn't find any method in java . please help if any one has any idea about it.`File fil =new File("C:\sujeet\efsfiles\iems\input"); FilenameFilter filter =new FilenameFilter(){ public boolean accept(File fil, String name){

 return name.
}};
File[] temp= fil.listFiles(filter);
public void SeeFiles(){
for(File file : temp){

 if(file.isFile())  {
    count++;
     System.out.println(file.getName());


 }`

回答1:

The FileNameFilter here won't work as you are looking for the file attribute level

Check this can be any help

package com.tmp;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Tmp implements DirectoryStream.Filter<Path> {

    public static void main( String[] args ) {

        Path dir = Paths.get( "d:\\tmp" ); // Folder to search for files

        try (DirectoryStream<Path> stream = Files.newDirectoryStream( dir, new Tmp() )) {

            for ( Path entry : stream ) {

                System.out.println( entry.getFileName() ); // file name which matched the accessed date
            }

        } catch ( IOException x ) {

            System.err.println( x );
        }
    }

    @Override
    public boolean accept( Path file ) throws IOException {

        try {

            BasicFileAttributes attr = Files.readAttributes( file, BasicFileAttributes.class );

            Date fileLastAccessedDate = new Date( attr.lastModifiedTime().toMillis() );

            Calendar cal = Calendar.getInstance();

            cal.setTime( fileLastAccessedDate );

            cal.set( Calendar.HOUR_OF_DAY, 0 );
            cal.set( Calendar.SECOND, 0 );
            cal.set( Calendar.MINUTE, 0 );
            cal.set( Calendar.MILLISECOND, 0 );

            SimpleDateFormat sdf = new SimpleDateFormat( "MM-dd-yyyy" );

            Date targetDate = sdf.parse( "2-20-2017" ); // date looking for the files

            return ( cal.getTime().equals( targetDate ) );

        } catch ( Exception x ) {

            System.err.println( x );

            return false;
        }
    }
}