Java中如何获取文件创建时间

Java中如何获取文件创建时间?有没有搞错!

直觉上本人以为java.io.File已经直接提供了获取文件创建时间的方法,悲剧的是,UNIX和Linux平台压根就没有文件创建时间的概念,因此,Java作为一门具备跨平台特性的语言,在API中提供获取文件创建时间的方法是不合适的。当然,任何平台都有文件最后修改时间的概念,java.io.File.lastModified()便是获取文件最后修改时间的方法。


那么,java中如何获取文件创建时间呢?方式不外乎两种:

1 强大的JNI,windows自己当然清楚如何获取文件创建时间了,用微软自己的C系列搞个dll吧。

2 不那么强大的Runtime,扔下C++那么久了,我才不要再搞什么dll,太烦了,直接用Runtime应付得了。


直接上代码:

package com.dancen.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Runtime获取文件创建时间示例
 * 
 * @author Dancen
 *
 */
public class FileCreatedDemo
{
	public static void main(String[] args)
	{
		try
		{
			String fileCreated = getFileCreated("D:\\xiyou.jpg");
			System.out.println(fileCreated);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public static String getFileCreated(String path)
	{
		if(null == path)
		{
			return null;
		}
		
		return getFileCreated(new File(path));
	}
	
	public static String getFileCreated(final File file)
	{
		if(null == file)
		{
			return null;
		}
		
		String rs = null;
		final StringBuilder sb = new StringBuilder();
		Process p = null;
		
		try
		{
			p = Runtime.getRuntime().exec(String.format("cmd /C dir %s /tc", file.getAbsolutePath()));
		}
		catch(IOException e)
		{
			return rs;
		}
		
		final InputStream is = p.getInputStream();
		final InputStreamReader ir = new InputStreamReader(is);
		final BufferedReader br = new BufferedReader(ir);
		
		Runnable runnable = new Runnable()
		{
			@Override
			public void run()
			{
				String data = null;
				
				try
				{
					while(null != (data = br.readLine()))
					{
						if(-1 != data.toLowerCase().indexOf(file.getName().toLowerCase()))
						{
							String[] temp = data.split(" +");
							
							if(2 <= temp.length)
							{
								String time = String.format("%s %s", temp[0], temp[1]);
								sb.append(time);
							}
							
							break;
						}
					}
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
				finally
				{
					try
					{
						if(null != br)
						{
							br.close();
						}
						
						if(null != ir)
						{
							ir.close();
						}
						
						if(null != is)
						{
							is.close();
						}
					}
					catch(IOException e)
					{
						e.printStackTrace();
					}
				}
			}
		};
		
		Thread thread = new Thread(runnable);
		thread.start();
		
		try
		{
			thread.join();
		} 
		catch(InterruptedException e)
		{
			e.printStackTrace();
		}
		
		if(0 != sb.length())
		{
			rs = sb.toString();
		}
		
		return rs;
	}
}

至于返回的时间字符串,仅精确到秒;时间格式是否与系统环境相关,需进一步确认。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值