java获取文件创建时间

来源:互联网 发布:vb是什么意思啊 编辑:程序博客网 时间:2024/05/18 03:42

方案一:

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