58

我想更改二进制文件的修改时间戳。这样做的最佳方法是什么?

打开和关闭文件是一个不错的选择吗?(我需要一个解决方案,在每个平台和 JVM 上更改时间戳的修改)。

4

7 回答 7

50

File 类有一个setLastModified方法。这就是 ANT 所做的。

于 2009-09-10T17:07:02.667 回答
27

我的 2 美分,基于@Joe.M 的回答

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);
}
于 2014-09-02T15:02:24.193 回答
14

由于File一个糟糕的抽象,最好使用Filesand Path

public static void touch(final Path path) throws IOException {
    Objects.requireNonNull(path, "path is null");
    if (Files.exists(path)) {
        Files.setLastModifiedTime(path, FileTime.from(Instant.now()));
    } else {
        Files.createFile(path);
    }
}
于 2017-06-05T16:59:58.350 回答
12

这是一个简单的片段:

void touch(File file, long timestamp)
{
    try
    {
        if (!file.exists())
            new FileOutputStream(file).close();
        file.setLastModified(timestamp);
    }
    catch (IOException e)
    {
    }
}
于 2013-03-30T17:49:30.190 回答
8

我知道Apache Ant有一个任务可以做到这一点。
查看Touch 的源代码(可以向您展示他们是如何做到的)

他们使用FILE_UTILS.setFileLastModified(file, modTime);, 哪个 使用ResourceUtils.setLastModified(new FileResource(file), time);, 哪个 使用org.apache.tools.ant.types.resources.Touchable, 由org.apache.tools.ant.types.resources.FileResource... 实现

基本上,它是对File.setLastModified(modTime).

于 2009-09-10T16:59:11.323 回答
6

这个问题只提到更新时间戳,但我想我还是把它放在这里。我一直在寻找像在 Unix 中一样的触摸,如果它不存在,它也会创建一个文件。

对于使用 Apache Commons 的任何人,都FileUtils.touch(File file)可以做到这一点。

这是(内联)的来源openInputStream(File f)

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);
    }
}
于 2013-07-24T16:42:27.987 回答
6

如果您已经在使用Guava

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

于 2015-12-14T11:35:19.507 回答