Pregunta

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

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

¿Fue útil?

Solución

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

Otros consejos

Mis 2 centavos, basados ??en @ 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);
}

Aquí hay un simple fragmento de código:

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

Sé que Apache Ant tiene una Task que hace exactamente eso.
Consulte el código fuente de Touch (que puede mostrarle cómo lo hacen)

Utilizan FILE_UTILS .setFileLastModified (file, modTime); , que utiliza ResourceUtils.setLastModified (nuevo FileResource (file), time); , que usa un org.apache.tools.ant.types.resources.Touchable , implementado por < código> org.apache.tools.ant.types.resources.FileResource ...

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

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

Para cualquier persona que use Apache Commons, hay FileUtils.touch (Archivo de archivo) que hace exactamente eso.

Aquí está el fuente de (en línea openInputStream (Archivo 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);
    }
}

Si ya está utilizando Guava :

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

Dado que File es una mala abstracción , es mejor usar Archivos 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);
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top