我想更改二进制文件的修改时间戳。这样做的最佳方法是什么?
打开和关闭文件是一个不错的选择吗?(我需要一个解决方案,在每个平台和 JVM 上更改时间戳的修改)。
File 类有一个setLastModified方法。这就是 ANT 所做的。
我的 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);
}
由于File
是一个糟糕的抽象,最好使用Files
and Path
:
public static void touch(final Path path) throws IOException {
Objects.requireNonNull(path, "path is null");
if (Files.exists(path)) {
Files.setLastModifiedTime(path, FileTime.from(Instant.now()));
} else {
Files.createFile(path);
}
}
这是一个简单的片段:
void touch(File file, long timestamp)
{
try
{
if (!file.exists())
new FileOutputStream(file).close();
file.setLastModified(timestamp);
}
catch (IOException e)
{
}
}
我知道Apache Ant有一个任务可以做到这一点。
查看Touch 的源代码(可以向您展示他们是如何做到的)
他们使用FILE_UTILS.setFileLastModified(file, modTime);
, 哪个 使用ResourceUtils.setLastModified(new FileResource(file), time);
, 哪个 使用org.apache.tools.ant.types.resources.Touchable
, 由org.apache.tools.ant.types.resources.FileResource
... 实现
基本上,它是对File.setLastModified(modTime)
.
这个问题只提到更新时间戳,但我想我还是把它放在这里。我一直在寻找像在 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);
}
}
如果您已经在使用Guava:
com.google.common.io.Files.touch(file)