使用Java模拟触摸命令

sin*_*pop 49 java file touch

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

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

Yis*_*hai 46

File类有一个setLastModified方法.这就是ANT的作用.

  • 除了shell`touch`创建文件,但事实并非如此. (9认同)
  • 除了已知的Android bug,File.setLastModified在大多数Android设备上都没有做任何事情. (2认同)

Aur*_*oms 20

我的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);
}
Run Code Online (Sandbox Code Playgroud)


Zac*_*h-M 11

这是一个简单的片段:

void touch(File file, long timestamp)
{
    try
    {
        if (!file.exists())
            new FileOutputStream(file).close();
        file.setLastModified(timestamp);
    }
    catch (IOException e)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不``file.createNewFile()`而不是`new FileOutputStream(file).close()`? (6认同)

sdg*_*sdh 11

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Von*_*onC 8

我知道Apache Ant有一个Task就是这么做的.
查看Touch源代码(可以告诉你他们是如何做到的)

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

基本上,这是一个电话File.setLastModified(modTime).


Rae*_*kye 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Joe*_*e23 6

如果您已经在使用番石榴:

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