我正在尝试获取 java 中文件的上次访问和创建日期,因此我使用 nio,但输出采用以下格式:
Last access time :: 2015-02-26T15:22:02.988862Z
Creation time :: 2015-02-26T15:22:02.988862Z
last modified time :: 2015-02-26T16:06:52.022666Z
是否有办法将它们转换为日期或日历对象,以便我可以获得正确的格式作为输出?
这是我的代码,
package com.home.test;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
public class TestRun {
public static void main(String[] args) {
TestRun tr = new TestRun();
tr.run();
}
private void run() {
File file = new File("D:/Test_Folder/File1.txt");
Path filPath = file.toPath();
BasicFileAttributes attrib = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
attrib = Files.readAttributes(filPath, BasicFileAttributes.class);
System.out.println("Last access time :: "+attrib.lastAccessTime());
System.out.println("Creation time :: "+attrib.creationTime());
System.out.println("last modified time :: "+attrib.lastModifiedTime());
} catch (Exception e) {
System.out.println("Error thrown"+e.toString());
}
}
}
最佳答案
嗯,不,时间戳以 FileTime
对象的形式出现。您可以通过将这些对象添加到 String
中来获取这些对象的 String
表示形式。
这些对象将相同的底层时间表示(自纪元以来的毫秒数)包装为 Date
或 Calendar
对象,因此,如果您愿意,是的,您可以获得以下之一那些。例如:
Calendar atime = Calendar.newInstance();
atime.setTimeInMillis(attrib.lastAccessTime().toMillis());
如果您希望采用日期
的形式,那么您可以继续
Date atimeAsDate = atime.getTime();
关于Java NIO 对象到日期的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28748138/