使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();
  }
    }
}