/**
* 检查是否有文件锁--方式一
* @param singleId 传入固定int数据即可
*/
public static boolean isUsing(int singleId) throws UnknownHostException{
try {
RandomAccessFile raf = null;
FileChannel channel = null;
FileLock lock = null;
// 在临时文件夹创建一个临时文件,锁住这个文件用来保证应用程序只有一个实例被创建.
File sf = new File(System.getProperty("java.io.tmpdir") + singleId + ".single");
sf.deleteOnExit();
sf.createNewFile();
raf = new RandomAccessFile(sf, "rw");
channel = raf.getChannel();
lock = channel.tryLock();
if (lock == null) {
// 如果没有得到锁,则程序退出.
// 没有必要手动释放锁和关闭流,当程序退出时,他们会被关闭的.
return false;
}
return true;
} catch (Exception e) {
log.error("检查时候有文件锁--异常"+e);
return false;
}
}
/**
* 检查是否有此进程存在--方式二
* @param processName 进程名字
*/
public static boolean isRunning(String processName)
{
BufferedReader bufferedReader = null;
try
{
Process proc = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq "
+ processName
+ "\"");
bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
if (line.contains(processName)) //判断是否存在
{
return true;
}
}
return false;
}
catch (Exception ex)
{
ex.printStackTrace();
return false;
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (Exception ex)
{
}
}
}
}
java--swing--程序单开的判断
最新推荐文章于 2021-02-16 13:37:39 发布