Home Tutorial Java Io Java read latest file

 
 

Java read latest file
Posted on: June 22, 2010 at 12:00 AM
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.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());
		System.out.println();
		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) {
			System.out.println(line);
		}
	}
}

Related Tags for Java read latest file: