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.listFiles();
            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]);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With