- How do I find the last modified file in a directory in Java?
- 9 Answers 9
- Как получить дату последнего изменения файла на Java
- 1. Атрибуты базового файла (NIO)
- 2. Файл.LastModified (устаревший ввод-вывод)
- Getting the last modified date of a file in Java
- 3 Answers 3
- Get last Modified Date of Files in a directory
- 4 Answers 4
- How to get the last modified date and time of a directory in java
- 7 Answers 7
How do I find the last modified file in a directory in Java?
Are you asking how to sort by last modified time? Or do you want an algorithm that finds the maximum of last modified time? These seem like obvious solutions; what are you really asking for?
9 Answers 9
private File getLatestFilefromDir(String dirPath) < File dir = new File(dirPath); File[] files = dir.listFiles(); if (files == null || files.length == 0) < return null; >File lastModifiedFile = files[0]; for (int i = 1; i < files.length; i++) < if (lastModifiedFile.lastModified() < files[i].lastModified()) < lastModifiedFile = files[i]; >> return lastModifiedFile; >
no. the greater the long value is, the later the file is modified. If that was the reason for the downvote, feel free to undo it 😉
@Bozho — using a comparator is no more «good practice», than using the int type is «good practice». The strongest you can say is that comparators are a good (partial) solution for many programming problems.
You could get an index out of bounds if the directory is empty. You should not assign files[0] to lastModifiedFile outside of the loop.
- You can get the last modified time of a File using File.lastModified() .
- To list all of the files in a directory, use File.listFiles() .
Note that in Java the java.io.File object is used for both directories and files.
import org.apache.commons.io.comparator.LastModifiedFileComparator; import org.apache.commons.io.filefilter.WildcardFileFilter; . . /* Get the newest file for a specific extension */ public File getTheNewestFile(String filePath, String ext) < File theNewestFile = null; File dir = new File(filePath); FileFilter fileFilter = new WildcardFileFilter("*." + ext); File[] files = dir.listFiles(fileFilter); if (files.length >0) < /** The newest file comes first **/ Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE); theNewestFile = files[0] >return theNewestFile; >
Just change the filter code to have only one File and the accept method should simply compare the two time stamps.
class TopFileFilter implements FileFilter < File topFile; public boolean accept(File newF) < if(topFile == null) topFile = newF; else if(newF.lastModified()>topFile.lastModified()) topFile = newF; return false; > >
Now, call dir.listFiles with an instance of this filter as argument. At the end, the filter.topFile is the last modified file.
You can retrieve the time of the last modification using the File.lastModified() method. My suggested solution would be to implement a custom Comparator that sorts in lastModified()-order and insert all the Files in the directory in a TreeSet that sorts using this comparator.
SortedSet modificationOrder = new TreeSet(new Comparator() < public int compare(File a, File b) < return (int) (a.lastModified() - b.lastModified()); >>); for (File file : myDir.listFiles()) < modificationOrder.add(file); >File last = modificationOrder.last();
The solution suggested by Bozho is probably faster if you only need the last file. On the other hand, this might be useful if you need to do something more complicated.
Как получить дату последнего изменения файла на Java
В Java мы можем использовать атрибуты `Basicfileattributes.время последнего изменения()`, чтобы получить дату последнего изменения файла.
В Java мы можем использовать Files.readAttributes() для получения метаданных или атрибута файла, а затем LastModifiedTime() для отображения даты последнего изменения файла.
Path file = Paths.get("/home/mkyong/file.txt"); BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class); System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
1. Атрибуты базового файла (NIO)
В этом примере используется java.nio. * для отображения атрибутов файла или метаданные – время создания, время последнего доступа и время последнего изменения.
package com.mkyong.io.howto; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; public class GetLastModifiedTime1 < public static void main(String[] args) < String fileName = "/home/mkyong/file.txt"; try < Path file = Paths.get(fileName); BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class); System.out.println("creationTime: " + attr.creationTime()); System.out.println("lastAccessTime: " + attr.lastAccessTime()); System.out.println("lastModifiedTime: " + attr.lastModifiedTime()); >catch (IOException e) < e.printStackTrace(); >> >
creationTime: 2020-07-20T09:29:54.627222Z lastAccessTime: 2020-07-21T12:15:56.699971Z lastModifiedTime: 2020-07-20T09:29:54.627222Z
Атрибут BasicFileAttributes также работает для каталога, и мы можем использовать тот же код для отображения времени последнего изменения каталога.
Дальнейшее чтение Прочитайте этот пример, чтобы преобразовать файловое время в другой формат даты и времени .
2. Файл.LastModified (устаревший ввод-вывод)
Для устаревшего ввода-вывода мы можем использовать File.LastModified() , чтобы получить время последнего изменения; метод возвращает длинное значение, измеренное в миллисекундах с момента [эпохи](https://en.wikipedia.org/wiki/Epoch_ (вычисления). Мы можем использовать SimpleDateFormat , чтобы сделать его более удобочитаемым форматом.
package com.mkyong.io.howto; import java.io.File; import java.text.SimpleDateFormat; public class GetLastModifiedTime2 < public static void main(String[] args) < String fileName = "/home/mkyong/test"; File file = new File(fileName); System.out.println("Before Format : " + file.lastModified()); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); System.out.println("After Format : " + sdf.format(file.lastModified())); >>
Before Format : 1595237394627 After Format : 07/20/2020 17:29:54
Getting the last modified date of a file in Java
I’m making a basic file browser and want to get the last modified date of each file in a directory. How might I do this? I already have the name and type of each file (all stored in an array), but need the last modified date, too.
3 Answers 3
Path path = Paths.get("C:\\1.txt"); FileTime fileTime; try < fileTime = Files.getLastModifiedTime(path); printFileTime(fileTime); >catch (IOException e)
where printFileName can look like this:
private static void printFileTime(FileTime fileTime) < DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss"); System.out.println(dateFormat.format(fileTime.toMillis())); >
The answer is correct and well explained, but please don’t teach the young ones to use the long outmoded and notoriously troublesome SimpleDateFormat class. Instead, since Java 8, use FileTime.toInstant() , convert the Instant to ZonedDateTime and either just print it or format it using a DateTimeFormatter .
You could do the following to achieve the result: Explained the returns types etc. Hope it helps you.
File file = new File("\home\noname\abc.txt"); String fileName = file.getAbsoluteFile().getName(); // gets you the filename: abc.txt long fileLastModifiedDate = file.lastModified(); // returns last modified date in long format System.out.println(fileLastModifiedDate); // e.g. 1644199079746 Date date = new Date(fileLastModifiedDate); // create date object which accept long SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // this is the format, you can change as you prefer: 2022-02-07 09:57:59 String myDate = simpleDateFormat.format(date); // accepts date and returns String value System.out.println("Last Modified Date of the FileName:" + fileName + "\t" + myDate); // abc.txt and 2022-02-07 09:57:59
Get last Modified Date of Files in a directory
As of now it just displays the last modified date of the directory on all files. Any help would be greatly appreciated!
4 Answers 4
In your question, you are pointing a Directory, not a File.
File file = new File(Environment.getExternalStorageDirectory() + dir); private final Activity context; Date lastModified = new Date(file.lastModified()); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); String formattedDateString = formatter.format(lastModified);
The idea is to get a Directory and iterate searching for the Last modified date of all files. The following question may help: How to get only 10 last modified files from directory using Java?
File images = new File("YourDirectoryPath"); long[] fileModifieDate = new long[images.listFiles().length]; int i=0; File[] imagelist = images.listFiles(new FilenameFilter() < public boolean accept(File dir, String name) < File file = new File(dir, name); fileModifieDate[i++] = file.lastModified(); return true; >>); // Here, max is the last modified date for this directory // Here, Long array **fileModifieDate** will give modified time of all files, which you can also access from Files array // if you want the last modified file in the directory you can do this: File[] maxModifiedDate = images.listFiles(new FilenameFilter() < public boolean accept(File dir, String name) < File file = new File(dir, name); return file.lastModified() == max; >>); // Now **maxModifiedDate** File array will have only one File, which will have max modified date.
For your case, this would be helpful:
public class MyAdapter extends ArrayAdapter < String dir = "/FileDirectory/"; File myFolder= new File(Environment.getExternalStorageDirectory() + dir); if(myFolder.exists())< File[] filelist = myFolder.listFiles(new FilenameFilter() < public boolean accept(File dir, String name) < return true; >>); >
// Now you have a filelist array of Files. If you want lastModified data, you can fetch from each individual file as you were doing previously:
private final Activity context; Date lastModified = new Date(file.lastModified()); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); String formattedDateString = formatter.format(lastModified); private String dateFormat = "dd/MM/yyyy HH:mm:ss";
How to get the last modified date and time of a directory in java
See, the problem is that in Java, we can get lastmodified date by filename.lastModified() . But in Windows, what is happening is that whenever a file is modifed, only that file’s date and time are getting modified, not the whole folder’s. So I want to know when was the last time even one single file was modified in that folder, using Java?
7 Answers 7
Find the latest (largest) lastModified() in the directory’s files, or if there are none use the directory’s itself:
public static Date getLastModified(File directory) < File[] files = directory.listFiles(); if (files.length == 0) return new Date(directory.lastModified()); Arrays.sort(files, new Comparator() < public int compare(File o1, File o2) < return new Long(o2.lastModified()).compareTo(o1.lastModified()); //latest 1st >>); return new Date(files[0].lastModified()); >
FYI this code has been tested (and it works).
Isnt a sort unnecessary? Why not just iterate through and keep track of the most recent modification?
@Bohemian I have a folder in the sdcard of my android phone and I delete a file manually from it. But when I get the last update time from above code , it doesn’t keep the time of deletion as the last update time. Why ?
Hi @Bohemian♦ there is a bug as @prateek said. You need to compare your result with the directory’s last modified time, because in case of deletion the last modified time is actually the directory’s last modified time.
Files.listFiles () will take a long time to execute if all you’re looking to check for is a single file being modified. Is there any way without using listFiles ()?
I have written a small piece of code which does a recursive search within all subdirectories and returns the latest modification date. It does a deep search, so you may not want to run it on the root directory or so. Here is the code (I have not tested it rigorously):
private static long getLatestModifiedDate(File dir) < File[] files = dir.listFiles(); long latestDate = 0; for (File file : files) < long fileModifiedDate = file.isDirectory() ? getLatestModifiedDate(file) : file.lastModified(); if (fileModifiedDate >latestDate) < latestDate = fileModifiedDate; >> return Math.max(latestDate, dir.lastModified()); >
It assumes that the supplied File is a directory, and also returns a long not a Date per se. You may convert long to Date by using the Date ‘s constructor if required (which is normally not needed).
Here is a Java 7 solution using FileTime and Path :
import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.text.SimpleDateFormat; import static java.nio.file.FileVisitResult.CONTINUE; public class NewestFileVisitor extends SimpleFileVisitor < private FileTime newestFileTime; private String targetExtension; public NewestFileVisitor(String targetExtension) < this.newestFileTime = FileTime.fromMillis(0); this.targetExtension = targetExtension; >@Override public FileVisitResult visitFile(Path filePath, BasicFileAttributes basicFileAttributes) throws IOException < if (filePath.toString().endsWith(targetExtension)) < FileTime lastModified = Files.getLastModifiedTime(filePath); // Newer? if (lastModified.compareTo(newestFileTime) >0) < newestFileTime = lastModified; >> return CONTINUE; > public String getLastModified() < SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a"); long milliseconds = newestFileTime.toMillis(); return simpleDateFormat.format(milliseconds); >>
String folder = ". "; NewestFileVisitor fileVisitor = new NewestFileVisitor(".txt"); Files.walkFileTree(Paths.get(folder), fileVisitor); System.out.println(fileVisitor.getLastModified());
This has been derived off the Oracle tutorial from here.