Created
October 26, 2011 18:13
-
-
Save fpersson/1317203 to your computer and use it in GitHub Desktop.
lockfile for android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test.demo; | |
import java.io.File; | |
import java.io.RandomAccessFile; | |
import java.nio.channels.FileChannel; | |
import java.nio.channels.FileLock; | |
import java.util.Date; | |
import android.app.Activity; | |
import android.os.Bundle; | |
import android.util.Log; | |
/** | |
* @author fredrik persson | |
* a quick android version, writing to /mnt/sdcard | |
*/ | |
public class demo extends Activity { | |
/** Called when the activity is first created. */ | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.main); | |
Log.i("Demo", "Locking file..."); | |
Date now = new Date(); | |
File file = new File("/mnt/sdcard/myfile"); | |
try{ | |
FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); | |
FileLock lock = channel.lock(); | |
if(!file.exists()){ | |
file.createNewFile(); | |
Log.i("Demo","Createing file"); | |
}else{ | |
Log.i("Demo","modify file"); | |
file.setLastModified(now.getTime()); | |
} | |
lock.release(); | |
channel.close(); | |
}catch(Exception e){ | |
Log.i("Demo","Err: "+e.getMessage()); | |
} | |
try { | |
Thread.sleep(5000); | |
} catch (InterruptedException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
Log.i("Demo","Current unixtime is: "+Long.toString(now.getTime())); | |
Log.i("Demo","File last modified:" +Long.toString(file.lastModified())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment