Java get last modified file

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"; 

Источник

Читайте также:  Переменная окружения java path

How do I get the last modification time of a Java resource?

Can someone please tell me a reliable way to get the last modification time of a Java resource? The resource can be a file or an entry in a JAR.

I didn’t even know JARs could have timestamps in them, but given it is like ZIP, I’m not entirely surprised. Interesting.

@Amigable Clark Kant — just a note, but the JAR format will get an update with Java 7, so assumptions about it being a ZIP file may no longer hold.

5 Answers 5

If you with «resource» mean something reachable through Class#getResource or ClassLoader#getResource, you can get the last modified time stamp through the URLConnection:

URL url = Test.class.getResource("/org/jdom/Attribute.class"); System.out.println(new Date(url.openConnection().getLastModified())); 

Be aware that getLastModified() returns 0 if last modified is unknown, which unfortunately is impossible to distinguish from a real timestamp reading «January 1st, 1970, 0:00 UTC».

Works in Swing, but not in Android. In Android I always get 0, although the accessible jarfile has a non-zero last modified date.

@j4nbur53: The JAR file you are compiling against? That one is not available at run time. No idea if the time stamp is retained in the Android APK file. Even if the language is similar, the Android runtime is very different from the Java runtime.

The APK file on Android is also a JAR file, you get URLs to entries by a simple getResource() call. But the implementation on Android differes from the one on Swing for example. The JarURLConnection does not implement getHeader() by delegating to the underlying jar file so that in the end annoyingly it doesn’t work on Android. (One can inspect both sources and find the difference in implementation)

«which unfortunately is impossible to distinguish from a real timestamp» Unless you got some very old files lying around I don’t think it will be hard to distinguish between real last-modified dates and Jan. 1 1970 🙂

@jarnbjo True. But in practice it is rarely a problem. One advantage though. This magic EPOCH date allows me to fill in 1/1/1970 as birthdate on websites that I don’t want to give my personal details, safely in the knowledge that in the DB there will be just the value 0 🙂

The problem with url.openConnection().getLastModified() is that getLastModified() on a FileURLConnection creates an InputStream to that file. So you have to call urlConnection.getInputStream().close() after getting last modified date. In contrast JarURLConnection creates the input stream when calling getInputStream().

@nullsector76 Leaving a stream open always leads to a resource leak. You can only optimize by using api that does not open any stream.

Apache Commons VFS provides a generic way of interacting with files from different sources. FileObject.getContent() returns a FileContent object which has a method for retreiving the last modified time.

Here is a modified example from the VFS website:

import org.apache.commons.vfs.FileSystemManager; import org.apache.commons.vfs.FileObject; . FileSystemManager fsManager = VFS.getManager(); FileObject jarFile = fsManager.resolveFile( "jar:lib/aJarFile.jar" ); System.out.println( jarFile.getName().getBaseName() + " " + jarFile.getContent().getLastModifiedTime() ); // List the children of the Jar file FileObject[] children = jarFile.getChildren(); System.out.println( "Children of " + jarFile.getName().getURI() ); for ( int i = 0; i

sounds overly complicated. I wound up using the java zip api then using the last modified. I also iterated through them and then compared the most likely non modified stamp in a modified jar.

I am currently using the following solution. The solution is the same like most of the other solutions in its initial steps, namely some getResource() and then openConnection().

But when I have the connection I am using the following code:

/** * 

Retrieve the last modified date of the connection.

* * @param con The connection. * @return The last modified date. * @throws IOException Shit happens. */ private static long getLastModified(URLConnection con) throws IOException < if (con instanceof JarURLConnection) < return ((JarURLConnection)con).getJarEntry().getTime(); >else < return con.getLastModified(); >>

The above code works on android and non-android, it returns the last modified date of the entry inside the ZIP if the resources is found inside an archive, otherwise it returns what it gets from the connection.

P.S.: The code still needs some brushing, there are some border cases where getJarEntry() is null.

Here is my code for getting the last modification time of your JAR file or compiled class (when using an IDE ).

import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.attribute.FileTime; import java.text.DateFormat; import java.util.Date; import java.util.Enumeration; import java.util.Locale; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; public class ProgramBuildTime < private static String getJarName() < ClassgetCurrentClass() < return new Object() <>.getClass().getEnclosingClass(); > private static boolean runningFromJAR() < String jarName = getJarName(); return jarName.endsWith(".jar"); >public static String getLastModifiedDate() throws IOException, URISyntaxException < Date date; if (runningFromJAR()) < String jarFilePath = getJarName(); try (JarFile jarFile = new JarFile(jarFilePath)) < long lastModifiedDate = 0; for (Enumerationentries = jarFile.entries(); entries.hasMoreElements(); ) < String element = entries.nextElement().toString(); ZipEntry entry = jarFile.getEntry(element); FileTime fileTime = entry.getLastModifiedTime(); long time = fileTime.toMillis(); if (time >lastModifiedDate) < lastModifiedDate = time; >> date = new Date(lastModifiedDate); > > else < ClasscurrentClass = getCurrentClass(); URL resource = currentClass.getResource(currentClass.getSimpleName() + ".class"); switch (resource.getProtocol()) < case "file": date = new Date(new File(resource.toURI()).lastModified()); break; default: throw new IllegalStateException("No matching protocol found!"); >> DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US); return dateFormat.format(date); > > 

Источник

How to get the file with latest lastModified date, in Java? [duplicate]

I have a directory of files that I need to check for changes. I consider it changed when one of the files has a modifiedDate newer than what I remembered from the last check (this is meant to be a cache dependency). What would be the fastest way of finding the latest modified file in a directory in Java? Maybe I’m too optimistic, but I’m explicitly looking for something that does not involve iterating all the files. Also, checking the directory modified date is not enough, as this only changes when the list of files inside changes, not when one of the files themselves is just modified.

Mmm. maybe there’s a workaround with evented IO. Sadly I’m not an expert on that but hope this gives a hint to anyone who is :). Good luck!

4 Answers 4

Even if you’re not looking to iterate all of the files, any third-party API you use to find this will iterate all of the files.

JDK 7 is intended to have java.nio.WatchService, which will apparently iterate through everything if it has to, but will use filesystem support to do exactly what you’ve asked for. On the minus side, that’s still in the future.

Thanks for the edit. 🙂 PS: Something like this is doable in .NET already (via System.IO.FileSystemWatcher ).

I’m very much looking forward to JDK 7 — if and when it’s actually done — as Java has some catchup to do with things C# devs now take for granted.

You must iterate all file names and extract the modification date.

It is pure java code but with a simple hack to improve performance.

I’m not sure if I understand this solution right: The basic operations are «get each file, look at its date». These are no faster than in an old-fashioned loop. So the speed improvement comes from doing the on-the-fly sorting?

You are right. Its no faster than a loop, but there is only one loop. Any other portable solution (pure java, no escaping to OS specific commands etc.) would need 1 loop to get all the files and then another loop over the files to get the last modified one. This one is saving that second loop by putting that logic in the first loop itself.

Thanks for clarifying. 🙂 However, to be completely honest: This particular solution was meant to be used in ColdFusion context, which runs on top of Java. You can operate Java objects in ColdFusion, but it’s impossible to implement interfaces or any other of the advanced stuff. I rather did not want to write my own Java class for this problem, so I left it at «do two loops». It’s good enough for now. PS: Use @ replies in comments or your responses might go unnoticed. (Only comments on the someone’s own post, like me commenting on your answer, don’t need an @ reply.)

Источник

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 

Источник

Оцените статью