Simulate touch command with Java

后端 未结 7 1362
太阳男子
太阳男子 2021-02-03 17:33

I want to change modification timestamp of a binary file. What is the best way for doing this?

Would opening and closing the file be a good option? (I require a solution

相关标签:
7条回答
  • 2021-02-03 18:08

    This question only mentions updating the timestamp, but I thought I'd put this in here anyways. I was looking for touch like in Unix which will also create a file if it doesn't exist.

    For anyone using Apache Commons, there's FileUtils.touch(File file) that does just that.

    Here's the source from (inlined 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题