Simulate touch command with Java

后端 未结 7 1374
太阳男子
太阳男子 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 17:44

    My 2 cents, based on @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);
    }
    
    0 讨论(0)
  • 2021-02-03 17:53

    I know Apache Ant has a Task which does just that.
    See the source code of Touch (which can show you how they do it)

    They use FILE_UTILS.setFileLastModified(file, modTime);, which uses ResourceUtils.setLastModified(new FileResource(file), time);, which uses a org.apache.tools.ant.types.resources.Touchable, implemented by org.apache.tools.ant.types.resources.FileResource...

    Basically, it is a call to File.setLastModified(modTime).

    0 讨论(0)
  • 2021-02-03 17:54

    The File class has a setLastModified method. That is what ANT does.

    0 讨论(0)
  • 2021-02-03 17:56

    Since File is a bad abstraction, it is better to use Files and 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);
        }
    }
    
    0 讨论(0)
  • 2021-02-03 17:58

    Here's a simple snippet:

    void touch(File file, long timestamp)
    {
        try
        {
            if (!file.exists())
                new FileOutputStream(file).close();
            file.setLastModified(timestamp);
        }
        catch (IOException e)
        {
        }
    }
    
    0 讨论(0)
  • 2021-02-03 18:07

    If you are already using Guava:

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

    0 讨论(0)
提交回复
热议问题