题
我想更改二进制文件的修改时间戳。这样做的最佳方式是什么?
打开和关闭文件是一个不错的选择吗? (我需要一个解决方案,在每个平台和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);
}
这是一个简单的片段:
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
,由 <实施code> org.apache.tools.ant.types.resources.FileResource ...
基本上,它是对 File.setLastModified(modTime)
的调用。
这个问题只提到更新时间戳,但我想我还是会把它放在这里。我在Unix中寻找触摸,如果它不存在,也会创建一个文件。
对于任何使用Apache Commons的人,都有 FileUtils.touch(文件文件)
就是这样做的。
这是 openInputStream(文件f))的标记“rel =”noreferrer“> source :
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);
}
}
如果您已经在使用番石榴:
<代码> com.google.common.io.Files.touch(文件)代码>
由于 File
是一个糟糕的抽象,最好使用 Files
和 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);
}
}