1. 程式人生 > >java獲取檔案建立時間

java獲取檔案建立時間

方案一:

   private static Date getCreateTime(String fullFileName){
        String str = null;
        try { 
            Process p = Runtime.getRuntime().exec("cmd /C dir \""+fullFileName+"\" /tc"); 
            InputStream is = p.getInputStream(); 
            BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
            int i = 0; 
            while ((str = br.readLine()) != null) {
                i++;
                if (i == 6) {
                 SimpleDateFormat sdf = new SimpleDateFormat(osDatetimeFormat);
                 Date d = sdf.parse(str.substring(0, 17));
                 return d;
                }
            }
        } catch (Exception e) {
         log.error(str+","+fullFileName+","+e.getMessage(), e);
        }
       Calendar cal = Calendar.getInstance();
       cal.set(1970, 0, 1, 0, 0, 0);
        return cal.getTime();
    }

本方案呼叫dos命令來獲取檔案的建立時間,是網上大多數人採用的方案,但是該方案存在效能問題。在本人的實際應用中存獲取10萬個檔案的建立時間,花費1個小時。

方案二:

    private static Date getCreateTime2(String fullFileName){
       Path path=Paths.get(fullFileName);  
       BasicFileAttributeView basicview=Files.getFileAttributeView(path, BasicFileAttributeView.class,LinkOption.NOFOLLOW_LINKS );
       BasicFileAttributes attr;
       try {
           attr = basicview.readAttributes();
           Date createDate = new Date(attr.creationTime().toMillis());
           return createDate;
       } catch (Exception e) {
          e.printStackTrace();
       }
      Calendar cal = Calendar.getInstance();
      cal.set(1970, 0, 1, 0, 0, 0);
      return cal.getTime();
    }
該方案經過測試獲取10萬個檔案的建立時間花費的時間為秒級。推薦使用。但該方案中的BasicFileAttributeView類只存java7以上版本。