Share on Google+Share on Google+

Java read latest file

In this section, you will learn how to read the last modified file.

Java read latest file

Java provides IO package to perform file operations. Here we are going to read the last modified file. For this, we have used the Comparator interface that compare the files 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. Then using the BufferedReader class, read that particular file.

Here is the code:

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(
		System.out.println("Files of the directory: ");
		for (int i = 0; i < files.length; i++) {
		System.out.println("Latest File is: "
				+ files[files.length - 1].getName());
		File file = new File(files[files.length - 1].getPath());
		String filename = file.getPath();
		BufferedReader reader = new BufferedReader(new FileReader(filename));
		String line = null;
		System.out.println("File Data");
		while ((line = reader.readLine()) != null) {


Posted on: June 22, 2010 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.