Проверка последнего изменения файла на сервере в Java
В Java у нас есть разные классы, такие как File, URL, который обеспечивает функциональность для чтения атрибутов файла, таких как время создания, время последнего доступа и время последнего изменения.
Метод 1 (с использованием атрибутов BasicFileAttributes)
В этом примере используется java.nio. * Для отображения метаданных файла и других атрибутов файла, таких как время создания, время последнего доступа и время последнего изменения.
Ява
// Java Program to get last modification time of the file 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[]) { // storing the path of the file in the string String fileName = "C:/Users/elavi/Desktop/File.txt" ; // used exception handling in order to catch the // exception // which may occur if there is no such file is // present at specified location // or the path of the file provided by the user is // incorrect try { // getting the path of the file Path file = Paths.get(fileName); // reading the attributes of the file BasicFileAttributes attr = Files.readAttributes( file, BasicFileAttributes. class ); // getting the last modification time of the // file System.out.println( "lastModifiedTime of File Is : " + attr.lastModifiedTime()); } catch (IOException e) { e.printStackTrace(); } } } |
Выходные данные: выходные данные содержат дату и время, когда в файл было внесено последнее изменение.
Метод 2 (с использованием File.lastModified)
Для устаревшего ввода-вывода можно использовать метод File.lastModified (), чтобы получить время последнего изменения файла, эта функция возвращает время последнего изменения файла в виде длинного значения, которое может быть измерено в миллисекундах. Мы можем использовать класс SimpleDataFormat, чтобы сделать возвращаемый результат более читабельным.
Ява
// Java Program to get last modification time of the file import java.io.File; import java.text.SimpleDateFormat; public class GFG_Article { public static void main(String[] args) { // path of the file String fileName = "C:/Users/elavi/Desktop/File.txt" ; File file = new File(fileName); // getting the last modified time of the file in the // raw format ie long value of milliseconds System.out.println( "Before Format : " + file.lastModified()); // getting the last modified time of the file in // terms of time and date 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())); } } |
Выходные данные: выходные данные содержат дату и время, когда в файл было внесено последнее изменение.
Метод 3 (с использованием класса URL)
Чтобы проверить последний модификация время загруженного файла на сервер, мы можем использовать класс URL, а затем можем получить время последней модификации файла.
Ява
// Java Program to get last modification time of the file 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 { // resource url URL u = new URL( URLConnection uc = u.openConnection(); uc.setUseCaches( false ); // getting the last modified time of the file // uploaded on the server long timestamp = uc.getLastModified(); System.out.println( "The last modification time of java.bmp is :" + timestamp); } } |
Выход
Вниманию читателя! Не прекращайте учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .