使java程序只運行一次,既只允許一個實例保留在內存中
主要是利用fileLock類來實現對文件加鎖,實現上述目的(多說無益,代碼如下):
package com.neonway.oneinstance;
import java.io.*;
import java.nio.channels.*;
public class OneInstance {
??? /**
???? * @param args
???? */
??? public static void main(String[] args) {
??? ?try {
??????????? System.out.println("progran start ...");
??????????? String filename = new String("test.txt");
??????????? File testFile = new File(filename);
??????????? RandomAccessFile raf;
??????????? FileChannel fc;
??????????? FileLock fl;
??????????? testFile.createNewFile();
??????????? if (testFile.canWrite()) {
??????????????? raf = new RandomAccessFile(testFile, "rw");
??????????????? fc = raf.getChannel();
??????????????? fl = fc.tryLock();
??????????????? if ((fl == null) || (fl.isValid() == false)) {
??????????????????? System.out.println("this is useing by another program!");
??????????????? } else {
??????????????? ?System.out.println("program running...");
??????????????????? Thread.sleep(30 * 1000);
??????????????????? fl.release();
??????????????? }
??????????????? raf.close();
??????????? }
?????????? System.out.println("program end ...");
??} catch (Exception e) {
???e.printStackTrace();
??}
??? }
}