How to get only 10 last modified files from directory using Java?
<p>HI, 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.</p>

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

<p>Any help will be aprreciated,
thank you</p>

<p>Here is the code:</p>

<pre><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 &gt; 0 ){
                    return 1;
                } else if( result &lt; 0 ){
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        System.out.println( Arrays.asList(files ));
    }
}
</code></pre>
