我想鎖定文件,然後對其進行一些更新,但每次我想要做這個操作時,我得到:java.nio.channels.overlappingFilelockException,我試圖添加這個異常的catch子句與這個和平的代碼:java:OverlappingFileLockException
catch(OverlappingFilelockException e){
lock.relese();
}
但這不適用於我。這裏是我的java代碼,我該怎麼做才能擺脫這種異常?
File file = new File("C://Users//user//Desktop//conf1.xml");
String content = '';
BufferedReader s;
BufferedWriter w;
RandomAccessFile ini=new RandomAccessFile(file, "rwd");;
FileLock lock= ini.getChannel().tryLock();;
def flowFile1=session.create();
DocumentBuilder dBuilder = null;
Document doc=null;
String start, startDate, endDate, runAs, makeVersion, patch;
try {
String sCurrentLine;
s = new BufferedReader(Channels.newReader(ini.getChannel(), "UTF-8"));
while ((sCurrentLine = s.readLine()) != null) {
content += sCurrentLine;
}
ini.seek(0);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult result1 = new StreamResult(bos);
try {
transformer.transform(source, result1);
} catch (TransformerException e) {
e.printStackTrace();
}
byte[] array = bos.toByteArray();
String data = bos.toString();
if (!data.isEmpty()) {
ini.setLength(0);
w = new BufferedWriter(Channels.newWriter(ini.getChannel(), "UTF-8"));
w.write(data);
lock.release();
w.close();
}
}catch (FileNotFoundException e) {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
finally {
lock.release();
ini.close();
}
請將您的代碼歸結爲最小,完整和可驗證的示例。我不認爲xml遊戲與java.nio錯誤有關。 – Heri
'這對我不起作用'不是問題描述。 – EJP