2009-09-10 59 views
42

我想更改二進制文件的修改時間戳。這樣做的最好方法是什麼?用Java模擬觸摸命令

打開和關閉文件是一個不錯的選擇? (我需要一個在每個平臺和JVM上修改時間戳的解決方案)。

+0

應該有人提出這是一個增強請求unix4j:https://github.com/tools4j/unix4j – 2017-05-21 05:37:43

+0

我不明白的關係標題和問題在這裏? – Lealo 2017-09-28 19:29:26

回答

41

File類有一個setLastModified方法。這就是ANT所做的。

+2

除了已知的Android錯誤之外,File.setLastModified在大多數Android設備上都沒有做任何事情。 – 2015-12-19 17:57:49

+2

除了shell'touch'創建文件,並沒有。 – 2016-08-07 21:58:12

8

這裏有一個簡單的片斷:

void touch(File file, long timestamp) 
{ 
    try 
    { 
     if (!file.exists()) 
      new FileOutputStream(file).close(); 
     file.setLastModified(timestamp); 
    } 
    catch (IOException e) 
    { 
    } 
} 
+5

爲什麼'file.createNewFile()'而不是'FileOutputStream(file).close()'? – Harvey 2015-08-20 19:04:45

5

這個問題只提到更新時間戳,但我想我把這個在這裏反正。我正在尋找像Unix一樣的觸摸,如果它不存在,它也會創建一個文件。

對於任何使用Apache Commons的人來說,FileUtils.touch(File file)就是這麼做的。

下面是從(內聯openInputStream(File f))的source

public static void touch(final File file) throws IOException { 
    if (file.exists()) { 
     if (file.isDirectory()) { 
      throw new IOException("File '" + file + "' exists but is a directory"); 
     } 
     if (file.canWrite() == false) { 
      throw new IOException("File '" + file + "' cannot be written to"); 
     } 
    } else { 
     final File parent = file.getParentFile(); 
     if (parent != null) { 
      if (!parent.mkdirs() && !parent.isDirectory()) { 
       throw new IOException("Directory '" + parent + "' could not be created"); 
      } 
     } 
     final OutputStream out = new FileOutputStream(file); 
     IOUtils.closeQuietly(out); 
    } 
    final boolean success = file.setLastModified(System.currentTimeMillis()); 
    if (!success) { 
     throw new IOException("Unable to set the last modification time for " + file); 
    } 
} 
17

我的2美分,基於@Joe.M answer

public static void touch(File file) throws IOException{ 
    long timestamp = System.currentTimeMillis(); 
    touch(file, timestamp); 
} 

public static void touch(File file, long timestamp) throws IOException{ 
    if (!file.exists()) { 
     new FileOutputStream(file).close(); 
    } 

    file.setLastModified(timestamp); 
} 
4

如果您已經使用Guava

com.google.common.io.Files.touch(file)

1

由於Filea bad abstraction,最好是使用FilesPath

public static void touch(final Path path) throws IOException { 
    Objects.requireNotNull(path, "path is null"); 
    if (Files.exists(path)) { 
     Files.setLastModifiedTime(path, FileTime.from(Instant.now())); 
    } else { 
     Files.createFile(path); 
    } 
}