这是一个防止程序运行多次的程序!有几个看不懂!
为什么这个程序能实现防止运行多次呢?
FileChannel,FileLock 这2个类到底有什么用啊.
文件通道到底是什么东东?
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.RandomAccess;
import javax.swing.JOptionPane;
public class A1 {
private FileChannel channel;//文件通道究竟 是什么东西?
private FileLock lock;//还有这个类.
private File file;
public A1(String lockFileName) {
file = new File(lockFileName);
}
public boolean isAppActive() {
try {
channel = new RandomAccessFile(file, "rw ").getChannel();
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
closeLock();
return true;
}
if (lock == null) {
closeLock();
return true;
}
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
closeLock();
deleteFile();
}
});
return false;
} catch (Exception e) {
closeLock();
return true;
}
}
protected void deleteFile() {
try {
file.delete();
} catch (Exception e) {
}
}
private void closeLock() {
try {
lock.release();
} catch (Exception e) {
}
try {
channel.close();
} catch (Exception e) {
}
}
public static void main(String[] args) {
A1 a = new A1( ".lock ");
if (a.isAppActive() == true)
JOptionPane.showMessageDialog(null, "已有一个程序在运行,程序退出 ");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
[解决办法]
给文件上锁,让它不能重复使用...