我想确保在读取 xml 文件时没有其他进程修改它。这是我的代码:
final File file = new File(configFilePath);
final FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
final FileLock lock = channel.tryLock();
if (lock == null) {
throw new MyCustomException(ErrorCode.configurationFileAlreadyLocked);
}
try {
final Unmarshaller u = JAXBContext.newInstance(Configuration.class).createUnmarshaller();
u.setSchema(getSchema());
return u.unmarshal(new StreamSource(file), Configuration.class).getValue();
} finally {
lock.release();
}
当我执行代码时,我得到一个带有 IOException 的 javax.xml.bind.UnmarshalException 作为原因:
Caused by: java.io.IOException: The process cannot access the file because another process has locked a portion of the file
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:220)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read(BufferedInputStream.java:237)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager$RewindableInputStream.read(XMLEntityManager.java:2977)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:702)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:186)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:772)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:200)
... 33 more
我会认为,因为获取锁的过程相同,所以不应该受到伤害。
如果我没有获得 FileLock,一切正常。
JAXB 是否已经为我处理文件锁定?
亲切的问候
塞巴斯蒂安