Yis*_*hai 46
File类有一个setLastModified方法.这就是ANT的作用.
Aur*_*oms 20
我的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);
}
Run Code Online (Sandbox Code Playgroud)
Zac*_*h-M 11
这是一个简单的片段:
void touch(File file, long timestamp)
{
try
{
if (!file.exists())
new FileOutputStream(file).close();
file.setLastModified(timestamp);
}
catch (IOException e)
{
}
}
Run Code Online (Sandbox Code Playgroud)
sdg*_*sdh 11
由于File
是一个糟糕的抽象,最好使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
我知道Apache Ant有一个Task就是这么做的.
查看Touch的源代码(可以告诉你他们是如何做到的)
他们使用FILE_UTILS.setFileLastModified(file, modTime);
,使用ResourceUtils.setLastModified(new FileResource(file), time);
,使用a 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);
}
}
Run Code Online (Sandbox Code Playgroud)