2009-09-10 12 views
42

バイナリファイルの変更タイムスタンプを変更したい。これを行うための最良の方法は何ですか?Javaでtouchコマンドをシミュレートする

ファイルの開閉は良い選択でしょうか? (タイムスタンプの変更がすべてのプラットフォームとJVMで変更されるソリューションが必要です)。

+0

誰かがunix4jする拡張要求としてこれを提出する必要があります。https://github.com/tools4j/unix4j –

+0

私は関係を理解し​​ていませんタイトルとここの質問の間に? – Lealo

答えて

41

FileクラスにはsetLastModifiedメソッドがあります。それがANTの行いです。

+2

既知のAndroidのバグがあることを除いて、File.setLastModifiedはほとんどのAndroidデバイスで何もしません。 –

+2

そして、シェル 'touch'がファイルを作成することを除いて、これはしません。 –

8

私はApache AntTaskを持っていることを知っています。
基本的に、それはFile.setLastModified(modTime)の呼び出しです... org.apache.tools.ant.types.resources.FileResourceによって実装org.apache.tools.ant.types.resources.Touchableを、使用している、彼らはResourceUtils.setLastModified(new FileResource(file), time);を使用FILE_UTILS.setFileLastModified(file, modTime);を、使用(彼らはそれを行う方法をお見せすることができます)source code of Touch

を参照してください。 。

8

ここでは簡単な抜粋です:

void touch(File file, long timestamp) 
{ 
    try 
    { 
     if (!file.exists()) 
      new FileOutputStream(file).close(); 
     file.setLastModified(timestamp); 
    } 
    catch (IOException e) 
    { 
    } 
} 
+5

なぜ、 'new FileOutputStream(file).close()'の代わりに 'file.createNewFile()'を使うのですか? – Harvey

5

は、この質問はタイムスタンプを更新言及が、私はとにかくここでこれを置くだろうと思っていました。私はUnixのようなタッチを探していましたが、存在しなければファイルを作成します。

Apache Commonsを使用している場合は、FileUtils.touch(File file)があります。ここで

は(openInputStream(File f)をインライン化)から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); 
    } 
} 
17

すでにGuavaを使用している場合@Joe.M answer

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); 
} 
4

に基づいて私の2セント、:

com.google.common.io.Files.touch(file)

1

Filea bad abstractionあるので、FilesPathを使用することをお勧めし:

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); 
    } 
} 
関連する問題