【Java开源代码栏目提醒】:网学会员--在 Java开源代码编辑为广大网友搜集整理了:ExclusiveRandomAccessFile.java绩等信息,祝愿广大网友取得需要的信息,参考学习。
import java.io.*;
/**
* Subclass of RandomAccessFile that always ensures that it
* has exclusive access to a file before opening it.
*/
public class ExclusiveRandomAccessFile
extends RandomAccessFile {
private static final String LOCK_FILE_SUFFIX = ".lck";
private File lockFile;
/**
* Open the named file using a lock file to ensure
* exclusive access.
* @param fileName The name of the file to open.
* @param mode This should either be "r" for read-only
* access or "rw" for read-write access.
* @exception FileSharingException
* If there is already a lock file for the named
* file.
* @exception IOException
* If there is a problem opening the file
*/
public static
ExclusiveRandomAccessFile openExclusive(String fileName,
String mode)
throws IOException {
File lockFile = new File(fileName+LOCK_FILE_SUFFIX);
if (!lockFile.createNewFile()) {
// lock file already exists
throw new FileSharingException(fileName);
} // if
return new ExclusiveRandomAccessFile(fileName,
mode,
lockFile);
} // openExclusive(String)
/**
* Construct a RandomAccessFile that has exclusive access
* to the given file.
* @param fileName The name of the file to open.
* @param mode This should either be "r" for read-only
* access or "rw" for read-write access.
* @param lockFile A file object that identifies the lock
* file.
*/
private ExclusiveRandomAccessFile(String fileName,
String mode,
File lockFile)
throws IOException {
super(fileName, mode);
this.lockFile = lockFile;
} // constructor(String, String)
/**
* Close this file.
*/
public synchronized void close() throws IOException {
if (lockFile!=null) { // If file is still open
lockFile.delete();
lockFile = null;
super.close();
} // if
} // close()
/**
* Ensure that the underlying file is closed before this
* object is garbage collected.
*/
protected void finalize() throws IOException {
close();
} // finalize()
} // class ExclusiveRandomAccessFile
上一篇:
EXCLUSIVEItemStateListenerDemo.java
下一篇:
法学专业毕业论文讲座