Here you can find the source of lockFile(File file)
Parameter | Description |
---|---|
file | a parameter |
public static FileLock lockFile(File file)
//package com.java2s; // are made available under the terms of the Eclipse Public License v1.0 import java.io.File; import java.io.FileOutputStream; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; public class Main { /**/*from w w w .jav a 2 s. c o m*/ * Locks a file for the current JVM. Will create the file if it does not * exist * * @param file * @return a FileLock object, or null if file could not be locked */ public static FileLock lockFile(File file) { FileOutputStream input = null; FileLock lock = null; try { input = new FileOutputStream(file); FileChannel fileChannel = input.getChannel(); lock = fileChannel.tryLock(); if (lock.isValid()) return lock; } catch (Exception e) { // Could not get a lock for some reason. return null; } finally { try { if (input != null && (lock == null || !lock.isValid())) { input.close(); } } catch (Exception ex) { } } return null; } }