Skip to content

Instantly share code, notes, and snippets.

@fpersson
Created October 26, 2011 17:50
Show Gist options
  • Save fpersson/1317138 to your computer and use it in GitHub Desktop.
Save fpersson/1317138 to your computer and use it in GitHub Desktop.
Lock a file and change last modified
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.Date;
/**
* @author fredrik Persson
*/
public class FileLocker {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("Locking a file...");
Date now = new Date();
File file = new File("myfile");
try{
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock = channel.lock();
if(!file.exists()){
file.createNewFile();
System.out.print("Createing file");
}else{
System.out.print("modify file");
file.setLastModified(now.getTime());
}
lock.release();
channel.close();
}catch(Exception e){
System.out.print(e.getMessage());
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("\nCurrent unixtime is: "+Long.toString(now.getTime()));
System.out.print("\nFile last modified:" +Long.toString(file.lastModified()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment