質問
バイナリファイルの変更タイムスタンプを変更したい。これを行うための最良の方法は何ですか?
ファイルを開いたり閉じたりするのは良い選択肢でしょうか? (タイムスタンプの変更がすべてのプラットフォームとJVMで変更されるソリューションが必要です。)
解決
Fileクラスには setLastModified メソッド。それがANTの機能です。
他のヒント
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 には Task はまさにそれを行います。
タッチのソースコード(どのように実行されるかを示すことができます)
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(File file)
まさにそれを実行します。
source from(インライン 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);
}
}
すでにグアバを使用している場合:
com.google.common.io.Files.touch(file)
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);
}
}