如何在Java中获取文件创建日期

没有官方的方法来获取Java中的文件创建日期。 但是,您可以使用以下解决方法在Windows平台中获取文件创建日期。

它是如何工作的

在Windows命令提示符下,键入命令以列出文件创建日期。

C:\>cmd /c dir c:\logfile.log /tc
 Volume in drive C has no label.
 Volume Serial Number is 0410-1EC3

 Directory of c:\

31/05/2010  08:05                14 logfile.log
               1 File(s)             14 bytes
               0 Dir(s)  35,389,460,480 bytes free

您需要“ 31/05/2010 08:05 ”。 这个想法是使用Java“ Runtime.getRuntime()。exec ”执行上面的命令,保留输出,然后逐行分析直到获得日期和时间。

在此示例中,它将获取文件(c:\\ logfile.log)的创建日期。

package com.mkyong.file;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class GetFileCreationDateExample
{
    public static void main(String[] args)
    {	
    
    	try{
    		
    		Process proc = 
    		   Runtime.getRuntime().exec("cmd /c dir c:\\logfile.log /tc");

    		BufferedReader br = 
    		   new BufferedReader(
    		      new InputStreamReader(proc.getInputStream()));
    		
    		String data ="";
    		
    		//it's quite stupid but work
    		for(int i=0; i<6; i++){
    			data = br.readLine();
    		}
    		
    		System.out.println("Extracted value : " + data);
    		
    		//split by space
    		StringTokenizer st = new StringTokenizer(data);
    		String date = st.nextToken();//Get date
    		String time = st.nextToken();//Get time
    		
    		System.out.println("Creation Date  : " + date);
    		System.out.println("Creation Time  : " + time);
    		
    	}catch(IOException e){

    		e.printStackTrace();

    	}
    	
    }
}

结果

Extracted value : 31/05/2010  08:05  14 logfile.log
Creation Date  : 31/05/2010
Creation Time  : 08:05

翻译自: https://mkyong.com/java/how-to-get-the-file-creation-date-in-java/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值