The java code traverses the files in the file directory to obtain the creation time and modification time of the file

The java code traverses the files in the file directory to obtain the creation time and modification time of the file

For example, the file directory is: D:/test folder contains these 5 files:Insert picture description here

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

The specific java code is as follows (jsa.java):

import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.io.File;
import java.text.*;
 
public class jsa 
{
	public  String file_name;//文件名(带路径)
	public  Date lastmodfiyTimeDate;//文件修改时间
	public  Date CreateTimeDate;//文件创建时间
	
	public  void set_fileInfo()
	{
		Path path = Paths.get(file_name);
		BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class,LinkOption.NOFOLLOW_LINKS);
		BasicFileAttributes attr;
		try 
		{
			attr = basicview.readAttributes();
			this.lastmodfiyTimeDate=new Date(attr.lastModifiedTime().toMillis());
			this.CreateTimeDate= new Date(attr.creationTime().toMillis());
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	//test main
	public static void main(String[] args) 
	{
		String path = "D:\\test";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println(path+ "路径下的所有文件");
		System.out.println("         文件名               "+"     lastModfiedTime	    "+"     creationTime	 ");
		File file = new File(path);		//获取其file对象
		File[] fs = file.listFiles();
		
		for(File f:fs)
		{
			if(f.isFile())
				{
				    String f1 = f.toString().replace("\\","/");
				    fileTimeInfo fti = new fileTimeInfo();
				    fti.file_name = f1;
				    fti.set_fileInfo();
				    System.out.println(f1+"     "+df.format(fti.lastmodfiyTimeDate)+"     "+df.format(fti.CreateTimeDate));
				}
		}
	}
}

operation result:

Insert picture description here
This is a problem I encountered during the development process, and then summarized by consulting the blog information,
reference materials:
https://blog.csdn.net/DCFANS/article/details/92840542 Java traverse all files under the folder
https://blog.csdn.net/weixin_38655836/article/details/80166565?utm_source=blogxgwz5 Java Get the creation time and modification time of the file
https://blog.csdn.net/yincan2011/article/details/76855061 java date size Compare

Guess you like

Origin blog.csdn.net/jing_zhong/article/details/104276445