バイナリファイルの変更タイムスタンプを変更したい。これを行うための最良の方法は何ですか?
ファイルを開いたり閉じたりするのは良いオプションでしょうか?(タイムスタンプの変更がすべてのプラットフォームとJVMで変更されるソリューションが必要です)。
File クラスにはsetLastModifiedメソッドがあります。それがANTの仕事です。
簡単なスニペットを次に示します。
void touch(File file, long timestamp)
{
try
{
if (!file.exists())
new FileOutputStream(file).close();
file.setLastModified(timestamp);
}
catch (IOException e)
{
}
}
ApacheAntにはまさにそれを行うタスクがあることを私は知っています。Touchのソースコードを
参照してください(これにより、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)