相关文章推荐
知识渊博的豆芽  ·  java - ...·  2 年前    · 

Java只能读取到文件的最后修改时间,不能获取创建时间,

创建时间是利用了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);
 }
}