我试图在解组之前锁定文件并在编组后释放。
public T lockedReadingFromFile(String filePath, Class<T> clas) {
T object = null;
JAXBContext context = null;
Unmarshaller unMarshaller = null;
try {
fileToBlock = new File(filePath);
file = new RandomAccessFile(fileToBlock, "rw");
FileChannel fileChannel = file.getChannel();
fileLock = fileChannel.tryLock();
if (fileLock != null) {
System.out.println("File is locked");
}
context = JAXBContext.newInstance(clas);
unMarshaller = context.createUnmarshaller();
object = (T) unMarshaller.unmarshal(fileToBlock);
} catch (JAXBException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return object;
}
但是代码在行内解组期间抛出异常object = (T) unMarshaller.unmarshal(fileToBlock);
File is locked
javax.xml.bind.UnmarshalException
- with linked exception:
[java.io.IOException: The process cannot access the file because another process has locked a portion of the file]
为什么会这样?