/**
* 获取文件的创建时间
* @param path 文件路径
* @return 返回创建的时间字符串(2020:11:17 22:11:00)
*/
public static StringBuffer getFileCreateTime(String path)
{
StringBuffer commandStr = Conver.nsb("cmd /C dir ");
commandStr.append(DelStr.changeStrInStr(Conver.nsb(path), "/", "\\")); // 路径下划线应该用"\", 而不是"/"
commandStr.append(" /tc");
StringBuffer str = Conver.nsb("");
try
{
Process p = Runtime.getRuntime().exec(commandStr.toString());
InputStream is = p.getInputStream();
int number = 0; // 接收读取的字符
int line = 0; // 换行符的数量, 时间在第5行之后
int totalCount = 0; // 第5行之后, 开始计算所有读取的字符, 时间字符串一共为17个字符长度
char ch = '\0'; // number转换为char
for (;;)
{
number = is.read();
if (number == -1)
{
break;
}
ch = (char)number;
// 如果是换行符, line增加
if (ch == '\n')
{
++line;
continue;
}
// 如果已经超过5行了, 说明这行之后就是时间字符串
if (line >= 5)
{
// 保存到str
str.append(ch);
++totalCount;
if (totalCount >= 17)
{
break;
}
}
}
}
catch (java.io.IOException exc)
{
exc.printStackTrace();
}
// 调整时间字符串
str = DelStr.changeStrInStr(str, "/", "-");
str = DelStr.changeStrInStr(str, " ", " ");
str.append(":00");
return str;
}
使用:
StringBuffer temp = FilePath.getFileCreateTime("c:/下载/1.txt");
System.out.println(temp);
运行效果: