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以上版本。

 

  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值