Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get only 10 last modified files from directory using Java?
    text
    copied!<p>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> <hr> <p>i'm beginner here sorry if made some mistakes using the forum.</p> <p>so for me i don't know how to insert the above in a new code.</p> <p>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.</p> <p>any help please</p> <p>Thank you</p> <pre><code>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&lt;File&gt;() { 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&lt;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) } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload