comando touch Simulate com Java
Pergunta
Eu quero mudar modificação timestamp de um arquivo binário. Qual é a melhor maneira para fazer isso?
abertura Would e fechar o arquivo ser uma boa opção? (I exigem uma solução onde a modificação da data e hora será alterada em todas as plataformas e JVM).
Solução
A classe File tem um setLastModified método . Isso é o que ANT faz.
Outras dicas
Os meus 2 centavos, com base em @ Joe.M resposta
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);
}
Aqui está um trecho simples:
void touch(File file, long timestamp)
{
try
{
if (!file.exists())
new FileOutputStream(file).close();
file.setLastModified(timestamp);
}
catch (IOException e)
{
}
}
Eu sei Apache Ant tem um Task que faz exatamente isso.
Veja a código-fonte do toque (que pode mostrar-lhe como fazê-lo)
Eles usam FILE_UTILS.setFileLastModified(file, modTime);
, que usa ResourceUtils.setLastModified(new FileResource(file), time);
, que usa um org.apache.tools.ant.types.resources.Touchable
, implementado pela org.apache.tools.ant.types.resources.FileResource
...
Basicamente, é uma chamada para File.setLastModified(modTime)
.
Esta pergunta só menciona atualizar o timestamp, mas eu pensei que eu ia colocar isso aqui de qualquer forma. Eu estava olhando para o toque como em Unix que também irá criar um arquivo se ele não existe.
Para qualquer um usando Apache Commons, há FileUtils.touch(File file)
que faz exatamente isso.
Aqui está o fonte a partir de (openInputStream(File f)
embutido):
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);
}
}
Se você já estiver usando Goiaba :
com.google.common.io.Files.touch(file)
Desde File
é uma abstração ruim , é melhor uso Files
e 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);
}
}