创建时间是利用了cmd命令获取的:
public class FileTest {
public static void main(String[] args) {
getCreateTime("d:\\test-1.txt")
getModifiedTime("d:\\test-1.txt")
}
public static void getCreateTime(String filePath) {
String strTime = null
try {
Process p = Runtime.getRuntime().exec("cmd /C dir " + filePath + "/tc")
InputStream is = p.getInputStream()
BufferedReader br = new BufferedReader(new InputStreamReader(is))
String line
while ((line = br.readLine()) != null) {
if (line.endsWith(".txt")) {
strTime = line.substring(0, 17)
break
}
}
} catch (IOException e) {
e.printStackTrace()
}
System.out.println("创建时间 " + strTime)
}
public static void getModifiedTime(String filePath) {
long time = new File(filePath).lastModified()
String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(time))
System.out.println("修改时间[1] " + ctime)
}
}
java中只能用java.io.File获得文件的最后修改时间,如下:
比如我在D盘有个文件夹a,现在要获取其创建时间:
File file = new File("D:\\a")
long time = file.lastModified()//返回文件最后修改时间,是以个long型毫秒数
String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(time))
System.out.println(ctime)
想要获得文件的创建时间,那么只能用java去掉命令实现了,若为windows系统,想要拿到创建时间必须依赖Windows系统的API,通过调CMD命令实现, 代码如下:
public static void main(String[] args) {try {
Process p = Runtime.getRuntime().exec("cmd /C dir d:\\test.txt /tc")
InputStream is = p.getInputStream()
BufferedReader br = new BufferedReader(new InputStreamReader(is))
String str
int i = 0
while ((str = br.readLine()) != null) {
i++
if (i == 6) {
System.out.println(str.substring(0, 17))
}
}
} catch (java.io.IOException exc) {
exc.printStackTrace()
}
}
在java中没有正式的方法来获取文件的创建时间,但是,可以使用下面的解决方法在Windows平台上获取文件的创建日期。java如何获取文件的创建日期
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=0i<6i++){
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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)