Simular comando táctil con Java


Quiero cambiar la marca de tiempo de modificación de un archivo binario. ¿Cuál es la mejor manera de hacer esto?

¿Abrir y cerrar el archivo sería una buena opción? (Necesito una solución donde la modificación de la marca de tiempo se cambiará en cada plataforma y JVM).

Author: Yishai, 2009-09-10

7 answers

La clase File tiene un método setLastModified. Eso es lo que hace ANT.

 44
Author: Yishai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-02 08:19:24

Mis 2 centavos, basado en @Joe.M respuesta

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);
}
 17
Author: Aurélien Ooms,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:56

Aquí hay un fragmento simple:

void touch(File file, long timestamp)
{
    try
    {
        if (!file.exists())
            new FileOutputStream(file).close();
        file.setLastModified(timestamp);
    }
    catch (IOException e)
    {
    }
}
 9
Author: Zach-M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-30 17:49:30

Sé que Apache Anttiene una Tarea que hace precisamente eso.
Vea el código fuente de Touch (que puede mostrarle cómo lo hacen)

Utilizan FILE_UTILS.setFileLastModified(file, modTime);, que utiliza ResourceUtils.setLastModified(new FileResource(file), time);, que utiliza un org.apache.tools.ant.types.resources.Touchable, implementado por org.apache.tools.ant.types.resources.FileResource...

Básicamente, es una llamada a File.setLastModified(modTime).

 8
Author: VonC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-26 00:33:25

Esta pregunta solo menciona la actualización de la marca de tiempo, pero pensé en poner esto aquí de todos modos. Estaba buscando un toque como en Unix que también creará un archivo si no existe.

Para cualquiera que use Apache Commons, hay FileUtils.touch(File file) eso hace precisamente eso.

Aquí está la fuente de (inlineado 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);
    }
}
 6
Author: Raekye,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-24 16:42:27

Si ya está usando Guayaba :

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

 4
Author: Joe23,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-14 11:35:19

Ya que File es una mala abstracción, es mejor usar Files y 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);
    }
}
 1
Author: sdgfsdh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-05 16:59:58