【问题标题】:Creation date of file in androidandroid中文件的创建日期
【发布时间】:2013-07-05 12:26:26
【问题描述】:

如何在android中获取文件的创建日期。我知道 file.lastModified(),但我确实需要创建日期,您可以在 OS Windows 中的文件属性中看到。

如果有人知道此任务的解决方案,请将其写在此消息下方。 谢谢!

【问题讨论】:

    标签: java android file date creation


    【解决方案1】:

    并非每个操作系统都支持创建日期。这就是为什么 Java 没有获取文件创建日期的方法的原因。我最近也遇到了这个问题。

    我所做的是将时间戳附加为文件的附录。

    File f = new File("myFile-" + System.currentTimeMillis());
    

    当您稍后查找您的文件时,您将能够提取附录并将其转换回日期以找到它的创建日期。

    String fileName = f.getName();
    String[] split = fileName.split("-");
    long timeStamp = 0;
    
    try {
        timeStamp = Long.parseLong(split[1]);
    } catch(NumberFormatException nfe) {
        nfe.printStackTrace();
    }
    
    System.out.println("Creation date for file " + f + " is " + new Date(timeStamp));
    

    【讨论】:

    • 实际上,我需要创建日期来对文件进行一些复制保护,所以这个解决方案不适合我。
    【解决方案2】:

    这仅适用于上述 API 26

    @RequiresApi(Build.VERSION_CODES.O)
    private fun getDate(file: File): String {
       val basicFileAttributes =
       Files.readAttributes(file.toPath(),BasicFileAttributes::class.java)
       val fileTimeStr = basicFileAttributes.creationTime().toString()
       return fileTimeStr.split("T")[0].split("-").reversed().joinToString("/")
    }
    
    @RequiresApi(Build.VERSION_CODES.O)
        private fun getTime(file: File): String{
        val basicFileAttributes = 
             Files.readAttributes(file.toPath(),BasicFileAttributes::class.java)     
        val fileTimeStr = basicFileAttributes.creationTime().toString()
        return fileTimeStr.split("T")[1].substringBeforeLast(":")
    }
    

    【讨论】:

      【解决方案3】:

      我找到了我的问题的解决方案,可能有人需要它: 您可以通过执行 bash 命令或脚本获取创建日期,如 here 所述

      stat <filepath>
      

      用于从 android 执行脚本:

      p = Runtime.getRuntime().exec("stat " + /mnt/sdcard01/somefile);
      p.waitFor();
      
      BufferedReader reader = 
           new BufferedReader(new InputStreamReader(
       p.getInputStream()));
      String line = reader.readLine();
      while (line != null) {
       line = reader.readLine();
      }
      

      【讨论】:

      • 在您分享的博客中,作者在 cmets 中承认 Creation Time 是一个错字,Linux/Unix 不支持创建时间。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 2014-08-13
      • 1970-01-01
      • 2011-06-17
      相关资源
      最近更新 更多