开发者

How to get only 10 last modified files from directory using Java?

开发者 https://www.devze.com 2023-02-10 09:47 出处:网络
i\'m beginner and i found an old thread about lastmodified files in java. What i want is to get only 10 recent files from a directory and move them to another directory.

i'm beginner and i found an old thread about lastmodified files in java. What i want is to get only 10 recent files from a directory and move them to another directory.

This code found in this forum is working well but it gets all files from a directory and sort them with date.

Any help will be aprreciated, thank you

Here is the code:

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;


public class Newest {
    public static void main(String[] args) {
        File dir = new File("C:\\your\\dir");
        File [] files  = dir.listFiles();
        Arrays.sort(files, new Comparator(){
            public int compare(Object o1, Object o2) {
                return compare( (File)o1, (File)o2);
            }
            private int compare( File f1, File f2){
                long result = f2.lastModified() - f1.lastModified();
                if( result > 0 ){
                    return 1;
                } else if( result < 0 ){
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        System.out.println( Arrays.asList(files ));
    }
}

i'm beginner here sorry if made some mistakes using the forum.

so for me i don't know how to insert the above in a new code.

And if i keep the first code, i would like to store the 10 recents files into another folder, i trie this but it puts all files in the directory.

any help please

Thank you

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.io.*;
import java.text.*;
import java.util.*;




    public class Newest
    {
        public static void main(String[] args)
        {
            File dir = new File("c:\\File");
            File[] files = dir.lis开发者_如何学GotFiles();
            Arrays.sort(files, new Comparator<File>()
            {
                public int compare(File f1, File f2)
                {
                    return Long.valueOf(f2.lastModified()).compareTo
                            (
                            f1.lastModified());
                }
            });
            //System.out.println(Arrays.asList(files));
            for(int i=0, length=Math.min(files.length, 12); i<length; i++) {
        System.out.println(files[i]);


    for (File f : files) {
            System.out.println(f.getName() + " " + sdf.format(new Date(f.lastModified())));
            File dir = new File("c://Target");
            boolean success = f.renameTo(new File(dir,f.getName()));
            if (!success)


            }
        }
    } 


In your code example, change:

System.out.println( Arrays.asList(files ));

to:

for(int i=0, length=Math.min(files.length, 10); i<length; i++) {
    System.out.println(files[i]);
}


Getting all the files and then sorting it is the only 'correct' way as per the specifications. But here is another approach which is a hack that uses the FileFilter as a visitor and does an on the fly insertion sort. On my machine the performance was about 4 times better on a directory with 2300 files (an image directory)

private File[] getTopFiles() {
    File dir = new File("C:\\icons_svr");
    SortFilter filter = new SortFilter(10);
    dir.listFiles(filter);      
    File[] topFiles = new File[10];
    return filter.topFiles.toArray(topFiles);
}

Code for InsertionSortFilter:

    class SortFilter implements FileFilter {

        final LinkedList<File> topFiles;
        private final int n;

        public SortFilter(int n) {
            this.n = n;
            topFiles = new LinkedList<File>();
        }

        public boolean accept(File newF) {
            long newT = newF.lastModified();

            if(topFiles.size()==0){
                //list is empty, so we can add this one for sure
                topFiles.add(newF);
            } else {
                int limit = topFiles.size()<n?topFiles.size():n;
                //find a place to insert
                int i=0;
                while(i<limit && newT <= topFiles.get(i).lastModified())
                    i++;

                if(i<limit){    //found
                    topFiles.add(i, newF);
                    if(topFiles.size()>n) //more than limit, so discard the last one. Maintain list at size n
                        topFiles.removeLast(); 
                }
            }
            return false;
        }

    }


The operating system doesn't take a sorting routine in asking for files. As a result, the only solution is to grab all files (to ensure that you don't skip over one of the ones you want) and to sort them yourself.

File systems do typically provide routines to grab files based on their file name, and Java exposes this through a list(...) which takes a FileFilter parameter.

In Java 1.7 (whenever they release it), there are new File oriented facilities which will allow you access to an abstraction of the underlying file system. With such facilities, one could conceivable create a file visitor, but that won't help the situation much, as you have no idea which files you may skip without actually looking at it's modification time. This means that even with a visiting interface, you'll still have to check the modification time of every file to make sure you didn't miss one of the ten files you wanted.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号