Android:如何获取文件的创建日期?

66 android

这是我的代码:

File TempFiles = new File(Tempfilepath);
if (TempFiles.exists()) {
    String[] child = TempFiles.list();
    for (int i = 0; i < child.length; i++) {
        Log.i("File: " + child[i] + " creation date ?");
        // how to get file creation date..?
    }
}
Run Code Online (Sandbox Code Playgroud)

Jor*_*sys 174

文件创建日期不可用,但您可以获取上次修改日期:

File file = new File(filePath);
Date lastModDate = new Date(file.lastModified());
Log.i("File last modified @ : "+ lastModDate.toString());
Run Code Online (Sandbox Code Playgroud)

  • 正如@CommonsWare在下面指出的那样,lastModified时间不是创建时间.创建时间不可用. (3认同)
  • 请先阅读,使用 last-modified 是一个选项,因为创建时间不可用。 (2认同)
  • 我想念的一点信息是File.lastModified是本地时间还是UTC的明确规范.大家一致认为它是UTC http://stackoverflow.com/questions/5264339/how-to-convert-a-date-to-utc,这也是我在半现代系统中所期望的.但为什么甲骨文的规范http://developer.android.com/reference/java/io/File.html#lastModified%28%29明确说明了这一点呢?"......自1970年1月1日午夜以来以毫秒为单位." 如果一个人充满偏执,可以解释为UTC 1970年1月1日,午夜或当地1970年1月1日午夜. (2认同)
  • 自1970年1月1日UTC以来,它存储在毫秒内,但您不必担心 - 它是"epoch"的标准定义.显示的任何日期可以本地时间或UTC时间或任何时区显示. (2认同)

小智 22

我就是这样做的

// Used to examplify deletion of files more than 1 month old
// Note the L that tells the compiler to interpret the number as a Long
final int MAXFILEAGE = 2678400000L; // 1 month in milliseconds

// Get file handle to the directory. In this case the application files dir
File dir = new File(getFilesDir().toString());

// Obtain list of files in the directory. 
// listFiles() returns a list of File objects to each file found.
File[] files = dir.listFiles();

// Loop through all files
for (File f : files ) {

   // Get the last modified date. Milliseconds since 1970
   Long lastmodified = f.lastModified();

   // Do stuff here to deal with the file.. 
   // For instance delete files older than 1 month
   if(lastmodified+MAXFILEAGE<System.currentTimeMillis()) {
      f.delete();
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 你没有回答这个问题.这是文件的最后修改日期. (4认同)
  • +1我喜欢这个答案最好的.我在一个帖子中运行它,它工作得很好.另外,喜欢var名称MAX_FILEAGE:P (2认同)

Com*_*are 21

文件创建日期不是Java File类公开的可用数据.我建议你重新考虑你在做什么,改变你的计划,这样你就不需要了.

  • @Fuzzy:这是最后修改的时间.文件修改后不是文件创建时间. (11认同)
  • 你为我们节省了很多时间 (2认同)

Ste*_*tes 6

从API级别26开始,您可以执行以下操作:

File file = ...;
BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
long createdAt = attr.creationTime().toMillis();
Run Code Online (Sandbox Code Playgroud)

  • 是的,但必须等待 3-4 年,直到 API 低于 26 的设备变得很少使用 (2认同)
  • @ user924:取决于您的用例。如果您要为自己或受控制的环境(小型团队)编写应用程序,今天就可以这样做。很高兴知道。 (2认同)

coo*_*994 5

还有另一种方式.在您修改文件夹之前,首次打开文件时保存lastModified日期.

long createdDate =new File(filePath).lastModified();
Run Code Online (Sandbox Code Playgroud)

然后当你关闭文件时

File file =new File(filePath);
file.setLastModified(createdDate);
Run Code Online (Sandbox Code Playgroud)

如果您在创建文件后已完成此操作,那么您将始终将createdDate作为lastModified日期.