我有以下方法将新数据保存到 xml 文件。它存储聊天记录:
public void addMessage(String from, String agentName, String msg, String time, String channel){
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
org.w3c.dom.Document doc = docBuilder.parse(filePath);
Node data = doc.getFirstChild();
org.w3c.dom.Element root = doc.createElement(channel);
org.w3c.dom.Element message = doc.createElement("message");
org.w3c.dom.Element _sender = doc.createElement("sender"); _sender.setTextContent(from);
org.w3c.dom.Element _content = doc.createElement("content"); _content.setTextContent(msg);
org.w3c.dom.Element _recipient = doc.createElement("recipient"); _recipient.setTextContent(agentName);
org.w3c.dom.Element _time = doc.createElement("time"); _time.setTextContent(time);
message.appendChild(_sender); message.appendChild(_content); message.appendChild(_recipient); message.appendChild(_time);
root.appendChild(message);
data.appendChild(root);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filePath));
transformer.transform(source, result);
}
catch(Exception ex){
System.out.println("Exceptionmodify xml");
}
}
我突然遇到的问题是例外情况Exceptionmodify xml
。我猜这是因为我从许多不同的线程访问这个方法,它搞砸了xml-file
.
有什么想法可以让这个线程安全吗?