Share on Google+Share on Google+

Java latest file

Advertisement
In this section, you will learn how to find the file which is generated or modified at last.

Java latest file

In this section, you will learn how to find the file which is generated or modified at last.

Description of code:

To find the last modified file, we have used the Comparator interface that compare the files  according to the file's last modification date and time and by using the Arrays.sort() method, we have sorted the files according to their modification time. After sorting, we have got the file name that was at the last.

Here is the code:

import java.io.*;
import java.util.*;

class LatestFile {
	public static void main(String[] args) throws Exception {
		File f = new File("C:/Answers/ImagesAndText");
		File[] files = f.listFiles();
		Arrays.sort(files, new Comparator() {
			public int compare(File f1, File f2) {
				return Long.valueOf(f1.lastModified()).compareTo(
						f2.lastModified());
			}
		});
		System.out.println("Files of the directory: ");
		for (int i = 0; i < files.length; i++) {
			System.out.println(files[i].getName());
		}
		System.out.println();
		System.out.println("Latest File is: "
				+ files[files.length - 1].getName());
	}
}

In the above code, we have used Comparator Interface that compare files according to their last modification time. The Arrays.sort() method sort the files accordingly. So this became easy as the file that comes at last will be latest file.

Output:

Files of the directory:
node.jpg
rose.jpg
barbie.jpg
hello.txt
examples.txt
java.txt
data.xml
pink.jpg
mail.txt

Latest File is: mail.txt

Advertisements

Advertisement

Posted on: August 1, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.