package com.smtscript.lib.file; import java.io.File; import java.io.RandomAccessFile; import java.nio.channels.FileLock; import java.nio.charset.Charset; public class JSFileLock { protected File _file; protected FileLock _fileLock; protected RandomAccessFile _randomAccessFile; protected Charset _charset; public JSFileLock(String fileName) throws Exception { _charset = Charset.forName("UTF-8"); _file = new File(fileName); _randomAccessFile = new RandomAccessFile(_file, "rw"); } public boolean tryLockWrite() throws Exception { if(_fileLock != null) throw new Exception("file has been locked"); _fileLock = _randomAccessFile.getChannel().tryLock(); return _fileLock != null; } public void waitLockWrite() throws Exception { if(_fileLock != null) throw new Exception("file has been locked"); _fileLock = _randomAccessFile.getChannel().lock(); } public void setFileLength(int length) throws Exception { _randomAccessFile.setLength((long)length); } public void setFilePos(int pos) throws Exception { _randomAccessFile.seek((long)pos); } public int getFilePos() throws Exception { return (int)_randomAccessFile.getFilePointer(); } public int getFileSize() throws Exception { return (int)_randomAccessFile.length(); } public void writeAllText(String text) throws Exception { _randomAccessFile.setLength(0); _randomAccessFile.write(text.getBytes(_charset)); } public String readAllText() throws Exception { _randomAccessFile.seek(0); int size = (int)_randomAccessFile.length(); byte[] data = new byte[size]; _randomAccessFile.read(data); return new String(data, _charset); } public void unlock() throws Exception { if(_fileLock != null) { _fileLock.release(); _fileLock = null; } } public void close(boolean deleteFile) throws Exception { unlock(); if(_randomAccessFile != null) { _randomAccessFile.close(); _randomAccessFile = null; } if(_file != null && deleteFile) { _file.delete(); _file = null; } } }