Checking Last Modification of a File On the Server in Java
Last Updated :
17 Nov, 2020
In Java, we have different classes like File, URL which provides the functionality to read the Attributes of file like creation time, last access time, and last modified time.
Method 1(Using BasicFileAttributes)
This example uses java.nio.* to display the metadata of the file and other file attributes like creation time, last access time, and last modified time.
Java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
public class GFG {
public static void main(String args[])
{
String fileName = "C:/Users/elavi/Desktop/File.txt" ;
try {
Path file = Paths.get(fileName);
BasicFileAttributes attr = Files.readAttributes(
file, BasicFileAttributes. class );
System.out.println(
"lastModifiedTime of File Is : "
+ attr.lastModifiedTime());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
Output: The output contains the date and time at which the last modification in the file was done.
Method 2(Using File.lastModified)
For the legacy IO, one can use File.lastModified() method in order to get the last modified time of the file, this function returns the last modified time of the file as a long value which can be measured in milliseconds. We can use SimpleDataFormat class to make the returned result more readable.
Java
import java.io.File;
import java.text.SimpleDateFormat;
public class GFG_Article {
public static void main(String[] args)
{
String fileName = "C:/Users/elavi/Desktop/File.txt" ;
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(
"The Date and Time at which the file was last modified is "
+ sdf.format(file.lastModified()));
}
}
|
Output: The output contains the date and time at which the last modification in the file was done.
Method 3(Using URL class)
To check the last modification time of the uploaded file on the server, we can make use of URL class, and then can fetch the last modification time of the file.
Java
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Date;
public class GFG {
public static void main(String[] args) throws Exception
{
URL u = new URL(
URLConnection uc = u.openConnection();
uc.setUseCaches( false );
long timestamp = uc.getLastModified();
System.out.println(
"The last modification time of java.bmp is :"
+ timestamp);
}
}
|
Output
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...