开发者

Changing File's last modified without closing it

File's last modified time is changed only when the file is closed.

public class Main {
    public static void main(String[] args) throws IOException {
        File f = new File("xyz.txt");

        FileWriter fwr = new FileWriter(f);
        System.out.println(f.lastModifie开发者_运维技巧d());
        fwr.write("asasdasdasd");
        System.out.println(f.setLastModified(System.currentTimeMillis()));
        fwr.flush();
        System.out.println(f.lastModified());
        fwr.close();
        System.out.println(f.lastModified());
        System.out.println(f.setLastModified(System.currentTimeMillis()));      
    }
}

Now, in my actual program, a file is opened and one of the thread keeps writing the file. several other threads need to know when was any data last written to the file.

Is there any possible way update last modified without closing the file? ( I know, having a static variable - long lastWriteTime in the thread that writes the file would work. but just curious to know if there is any other way, to change the last modified time without closing the file. )


Depending on what you actually want to achieve one of two methods may be appropriate:

  • use File.setLastModified() to directly manipulate the timestampe or
  • use f.flush() to ensure all data written is actually written to the disk.

Note that the OS and/or the file system may have a lower resolution of that timestamp than you hope for. For example FAT stores those timestamps with a 2-second resolution! Even more modern file systems are known to store only in a single-second resolution.

Also note that the behavior of the last modified timestamp varies a lot depending on the OS. On my Ubuntu, for example, only the write/flush modifies the timestamp, the close() doesn't!


Please keep in mind that the behaviour you see is highly dependend on OS and perhaps file system type. Hence, java can not and does not specify when file times are updated. Therefore, no , there is no portable way to do that in java.


What about using setLastModified()?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜