- Определение даты создания файла в Java
- 1. Обзор
- 2. Files.getAttribute
- 3. Файлы.Атрибуты чтения
- 4. Заключение
- Читайте ещё по теме:
- Java file time
- Files
- BasicFileAttributes
- Java file creation time
- Java file last modification time
- Java file last access time
- Author
- Getting File Creation Timestamp in Java
- Read file creation time in Java
- 2. Read creation time using Files.getAttribute(. ) method from JDK7
- 3. Determine file creation time using Files.readAttributes(. ) method
- 4. Read last modified time using File from java.io package
- 5. Conclusion
- File created time in java
- Call the following method:
- Create the following java file:
- The output will be:
Определение даты создания файла в Java
JDK 7 представил способ просмотра даты создания файла. Узнайте, что это такое.
1. Обзор
В JDK 7 появилась возможность получить дату создания файла.
В этом уроке мы узнаем, как получить к нему доступ через java.nio .
2. Files.getAttribute
Один из способов получить дату создания файла – использовать метод Files.getAttribute с заданным Путем :
Тип CreationTime – это FileTime , но из-за того, что метод возвращает Объект, мы должны привести его .
FileTime содержит значение даты в качестве атрибута метки времени. Например, он может быть преобразован в Instant с помощью метода to Instant () .
Если файловая система не хранит дату создания файла, то метод вернет null .
3. Файлы.Атрибуты чтения
Другой способ получить дату создания-с помощью Files.readAttributes , который для заданного Пути возвращает все основные атрибуты файла сразу:
Метод возвращает атрибуты BasicFileAttributes, которые мы можем использовать для получения основных атрибутов файла. Метод creation Time() возвращает дату создания файла как File Time .
На этот раз, если файловая система не хранит дату создания файла, то метод вернет дату последнего изменения . Если дата последнего изменения также не сохранена, то будет возвращена эпоха (01.01.1970).
4. Заключение
В этом уроке мы узнали, как определить дату создания файла в Java. В частности, мы узнали, что можем сделать это с помощью Files.getAttribute и Files.readAttributes .
Как всегда, код для примеров доступен на GitHub .
Читайте ещё по теме:
Java file time
In Java file time tutorial, we show how to determine file creation, last modification, and last access time in Java with Files and BasicFileAttributes .
Files
Files is a Java class that contains static methods that operate on files, directories, or other types of files. Mostly, these methods will delegate to the associated file system provider to perform the file operations.
BasicFileAttributes
BasicFileAttributes holds basic file attributes. These are attributes that are common to many file systems and consist of mandatory and optional file attributes, such as size of file creation time. BasicFileAttributes are retrieved with Files.readAttributes method.
Java file creation time
The file creation time in Java is retrieved with BasicFileAttributes.creationTime method.
package com.zetcode; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; public class JavaFileLastCreationTime < public static void main(String[] args) throws IOException < String fileName = "/home/jano/world.sql"; File myfile = new File(fileName); Path path = myfile.toPath(); BasicFileAttributes fatr = Files.readAttributes(path, BasicFileAttributes.class); System.out.printf("File creation time: %s%n", fatr.creationTime()); >>
This example prints the creation time of the specified file.
Java file last modification time
The BasicFileAttributes.lastModifiedTime method gets the last modification time of a file in Java.
package com.zetcode; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; public class JavaFileLastModifiedTime < public static void main(String[] args) throws IOException < String fileName = "/home/jano/world.sql"; File myfile = new File(fileName); Path path = myfile.toPath(); BasicFileAttributes fatr = Files.readAttributes(path, BasicFileAttributes.class); System.out.printf("Last modification time: %s%n", fatr.lastModifiedTime()); >>
This example prints the last modification time of the specified file.
Java file last access time
The last access time of a file in Java is retrieved with BasicFileAttributes.lastAccessTime method.
package com.zetcode; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; public class JavaFileLastAccessTime < public static void main(String[] args) throws IOException < String fileName = "/home/jano/world.sql"; File myfile = new File(fileName); Path path = myfile.toPath(); BasicFileAttributes fatr = Files.readAttributes(path, BasicFileAttributes.class); System.out.printf("Last access time: %s%n", fatr.lastAccessTime()); >>
This example prints the last access time of the specified file.
In this article we have determined the file creation, last modification, and last access time with Files and BasicFileAttributes .
Author
My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.
Getting File Creation Timestamp in Java
Learn to get the creation date and time of a file in Java using Java NIO APIs. This may be useful to compare timestamps of files before deleting the older files permanently.
The essential file attributes that we can read for a file are listed below. Note that some attributes may not be available in specific operating systems, and returned value will be JVM implementation-specific.
We may get UnsupportedOperationException if an attribute of the given type is not supported.
2. Using Files.getAttribute()
The getAttributes() retrieves the creation date and time of a file using the file attribute name creationTime .
Path filePath = Paths.get("c:/temp/data.txt"); FileTime creationTime = (FileTime) Files.getAttribute(filePath, "creationTime");
3. Using Files.readAttributes()
The readAttributes() method reads a file’s attributes as a bulk operation. It takes the file path and class type of the file attributes. For example,
- BasicFileAttributes: represents the basic attributes associated with a file in a filesystem.
- DosFileAttributes: represents file attributes in platforms like DOS and Samba.
- PosixFileAttributes: represents file attributes in UNIX. POSIX supports nine file permissions: read, write, and execute permissions for the file owner, members of the same group, and “everyone else.
BasicFileAttributes fileAttrs = Files.readAttributes(filePath, BasicFileAttributes.class); FileTime fileTime = fileAttrs.creationTime();
4. Converting in Different Time Units
We can use the FileTime.to(TimeUnit) method to convert the file creation time to another time elapsed since epoch (1970-01-01T00:00:00Z).
long millis = creationTime.to(TimeUnit.MILLISECONDS); long days = creationTime.to(TimeUnit.DAYS);
Similarly, we can also use HOURS, MINUTES, SECONDS, and MICROSECONDS time units.
To support the new Java 8 Date time classes, we can convert the creation time to Instant as well.
Instant instant = creationTime.toInstant();
This Java tutorial taught us to get the file creation time using the Java NIO’s Files class and its methods. These APIs were introduced in Java 7, so there was no direct solution to fetch the creation timestamp till Java 6.
Read file creation time in Java
In this article, we are going to show a way to determine file creation time in Java.
2. Read creation time using Files.getAttribute(. ) method from JDK7
From JDK 7 we can determine file creation time using java.nio.Files class.
Let’s check the first approach:
package com.frontbackend.java.io.attributes; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.attribute.FileTime; public class CreationDateUsingFilesGetAttrs < public static void main(String[] args) throws IOException < File file = new File("/tmp/frontbackend.txt"); FileTime creationTime = (FileTime) Files.getAttribute(file.toPath(), "creationTime"); System.out.printf("The file creation date and time is: %s%n", creationTime); >>
In this example, we make the use of Files.getAttribute(. ) method that takes file Path and attribute name, which is in this case: creationTime . The result type depends on the given attribute, so in our example, we need to cast return Object to FileTime class that holds timestamp value.
Note that if the filesystem doesn’t hold creation time of the files method Files.getAttribute(. ) will return null.
3. Determine file creation time using Files.readAttributes(. ) method
Reading all attributes using Files.readAttributes(. ) method is another way to get file creation time:
package com.frontbackend.java.io.attributes; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.attribute.BasicFileAttributes; public class CreationDateUsingFilesReadAttrs < public static void main(String[] args) throws IOException < File file = new File("/tmp/frontbackend.txt"); BasicFileAttributes attributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class); System.out.printf("The file creation date and time is: %s%n", attributes.creationTime()); >>
In this example we get BasicFileAttributes using Files.readAttributes(. ) method, and then get the attribute we are looking for: attributes.creationTime() .
This method is also an operating system dependent. When OS doesn’t store file creation times it will return last modified time.
4. Read last modified time using File from java.io package
In JDK 6 we don’t have dedicated API to determine file creation date straightforward. The best we can do here is to get the last modified time. Check the following example:
package com.frontbackend.java.io.attributes; import java.io.File; import java.util.Date; public class ModifiedDateUsingFile < public static void main(String[] args) < File file = new File("/tmp/frontbackend.txt"); Date lastModifiedTime = new Date(file.lastModified()); System.out.println(lastModifiedTime); >>
In this snippet, we create an instance of File class and use file.lastMofied() to get modified time as the timestamp.
5. Conclusion
In this article, we’ve learned how to get the file creation date in Java. We present two approaches from JDK 7 using java.nio.Files class and one example from JDK 6. Unfortunately below JDK 7 we don’t have dedicated API to determine file creation date but we can still get last modified time using old java.io package.
As always, the code for examples is available over on GitHub.
File created time in java
A file creation date can be accessed by reading the BasicFileAttributes from the Path :
Call the following method:
BasicFileAttributes attrs = Files.readAttributes(file.toPath(), BasicFileAttributes.class); FileTime time = attrs.creationTime();
Here an example accessing the creation date and time of a file in Java.
The code creates a File Object from the file path; then it reads the Path attributes using Files.readAttributes . The creation date and time can be accessed from there. The time is a FileTime Object, it is converted to a Date and formatted for rendering. The output String is written in the output.
Create the following java file:
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.text.SimpleDateFormat; import java.util.Date; public class FileCreationDate < public static void main(String[] argv)< File file = new File( "V:/tmp/test.txt" ); BasicFileAttributes attrs; try < attrs = Files.readAttributes(file.toPath(), BasicFileAttributes.class); FileTime time = attrs.creationTime(); String pattern = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String formatted = simpleDateFormat.format( new Date( time.toMillis() ) ); System.out.println( "The file creation date and time is: " + formatted ); >catch (IOException e) < e.printStackTrace(); >> >
The output will be:
The file creation date and time is: 2017-01-16 16:54:09