Java latest file


 

Java latest file

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

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

Ads