Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Java模拟touch命令_Java_File_Touch - Fatal编程技术网

用Java模拟touch命令

用Java模拟touch命令,java,file,touch,Java,File,Touch,我想更改二进制文件的修改时间戳。这样做的最佳方式是什么 打开和关闭文件是一个好的选择吗?(我需要一个解决方案,在每个平台和JVM上修改时间戳)。我知道有一个解决方案可以做到这一点。 查看(可以向您展示他们是如何做到的) 他们使用,它使用,它使用,由 基本上,它是对File.setLastModified(modTime)的调用,File类有一个方法。这就是ANT所做的。这里有一个简单的片段: void touch(File file, long timestamp) { try

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

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

我知道有一个解决方案可以做到这一点。
查看(可以向您展示他们是如何做到的)

他们使用,它使用,它使用,由


基本上,它是对
File.setLastModified(modTime)
的调用,File类有一个方法。这就是ANT所做的。

这里有一个简单的片段:

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

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

对于任何使用ApacheCommons的人来说,都有这样的功能

以下是from(内联的
openInputStream(文件f)
):

我的2美分,基于

如果您已经在使用:


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

既然
文件
是,最好使用
文件
路径

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);
    }
}

为什么不使用
file.createNewFile()
而不是
newfileoutputstream(file.close()
?除了存在已知的Android错误,file.setLastModified在大多数Android设备上不起任何作用。除了shell
touch
创建文件,但事实并非如此。应该有人将此作为增强请求提交给unix4j:我不理解标题和此处问题之间的关系?@Lealo see标题令人困惑,这是公认的答案。如果文件不存在,触摸会创建文件。应更改标题。file.exists和file.setLastModified调用之间存在竞争条件。也就是说,这段代码是反向的:首先你继续尝试,然后你做验尸诊断。
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);
}
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);
    }
}