Frage

Ich möchte Änderung Zeitstempel einer Binärdatei ändern. Was ist der beste Weg, dies zu tun?

Würde das Öffnen und Schließen der Datei eine gute Option sein? (Ich benötige eine Lösung, bei der die Änderung des Zeitstempels wird auf jeder Plattform und JVM geändert werden).

War es hilfreich?

Lösung

Die File-Klasse ein setLastModified Methode. Das ist, was ANT der Fall ist.

Andere Tipps

My 2 cents, basierend auf @ Joe.M beantworten

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

Hier ist ein einfaches Snippet:

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

Ich weiß Apache Ant hat eine Task die tut genau das.
Sehen Sie die Quellcode-Touch (die man zeigen kann, wie sie es tun)

Sie benutzen FILE_UTILS.setFileLastModified(file, modTime); , die ResourceUtils.setLastModified(new FileResource(file), time); verwendet, die verwendet eine org.apache.tools.ant.types.resources.Touchable , umgesetzt von org.apache.tools.ant.types.resources.FileResource ...

Im Grunde ist es ein Aufruf an File.setLastModified(modTime).

Diese Frage erwähnt nur den Zeitstempel zu aktualisieren, aber ich dachte, dass ich das sowieso hier setzen würde. Ich war für Berührung wie in Unix suchen, die auch eine Datei erstellen, wenn es nicht vorhanden ist.

Für jedermann mit Apache Commons, es ist FileUtils.touch(File file) die genau das tut.

Hier ist die Quelle aus (inlined 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);
    }
}

Wenn Sie bereits mit Guava :

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

scroll top