Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate touch command with Java

Tags:

java

file

touch

I want to change modification timestamp of a binary file. What is the best way for doing this?

Would opening and closing the file be a good option? (I require a solution where the modification of the timestamp will be changed on every platform and JVM).

like image 413
sinuhepop Avatar asked Sep 10 '09 16:09

sinuhepop


People also ask

What is touch in Java?

Overview. The touch command in Linux is a handy way to change the access time and modification time of a file or directory. It can also be used to create an empty file quickly. In this short tutorial, we'll see how to simulate this command in Java.

How do you write touch command?

Touch command Syntax to create a new file: You can create a single file at a time using touch command. The file which is created can be viewed by ls command and to get more details about the file you can use long listing command ll or ls -l command . Here file with name 'File1' is created using touch command.

What is touch in shell script?

The touch command's primary function is to modify a timestamp. Commonly, the utility is used for file creation, although this is not its primary function. The terminal program can change the modification and access time for any given file. The touch command creates a file only if the file doesn't already exist.

What is Unix touch?

The touch command is a standard program for Unix/Linux operating systems, that is used to create, change and modify timestamps of a file.


2 Answers

The File class has a setLastModified method. That is what ANT does.

like image 167
Yishai Avatar answered Sep 22 '22 14:09

Yishai


My 2 cents, based on @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); } 
like image 24
Mmmh mmh Avatar answered Sep 24 '22 14:09

Mmmh mmh