您好,我正在开发一个 swing 聊天应用程序,其中聊天历史记录存储在 xml 文件中。 在 NetBeans 项目中完成后,我能够获取 xml 文件并将其显示在表格中
但是当转换为 jar 文件时,我无法使用 xml 文件。 我尝试过各种方法,例如 getClass().getResource() 方法,但它检索的是 URL 而不是字符串,如果使用 toString() 方法转换为字符串,则它不能用作有效路径来解析xml 文件。
下面是代码-->
ServerFrame.java
public class ServerFrame extends javax.swing.JFrame {
public String historyFile;
public HistoryFrame historyFrame;
public History hist; }
public ServerFrame() {
historyFile=this.getClass().getResource("History.xml").toString();}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
hist = new History(historyFile);
historyFrame = new HistoryFrame(hist);
historyFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
historyFrame.setLocation(this.getLocation());
historyFrame.setVisible(true);
}
历史记录.java
public class History {
public String filePath;
public History(String filePath){
this.filePath = filePath;
}
public void addMessage(Message msg, String time){
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filePath);
Node data = doc.getFirstChild();
Element message = doc.createElement("message");
Element _sender = doc.createElement("sender"); _sender.setTextContent(msg.sender);
Element _content = doc.createElement("content"); _content.setTextContent(msg.content);
Element _recipient = doc.createElement("recipient"); _recipient.setTextContent(msg.recipient);
Element _time = doc.createElement("time"); _time.setTextContent(time);
message.appendChild(_sender); message.appendChild(_content); message.appendChild(_recipient); message.appendChild(_time);
data.appendChild(message);
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");
}
}
public void FillTable(HistoryFrame frame){
DefaultTableModel model = (DefaultTableModel) frame.jTable1.getModel();
try{
File fXmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("message");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
model.addRow(new Object[]{getTagValue("sender", eElement), getTagValue("content", eElement), getTagValue("recipient", eElement), getTagValue("time", eElement)});
}
}
}
catch(Exception ex){
System.out.println("Filling Exception");
}
}
我已将 xml 文件放在项目目录的 src 文件夹中。问题似乎出在 docBuilder.parse() 中,因为每次函数中都会生成异常,并且自系统路径以来它只接受字符串而不是 url文件的路径与文件的javapath不同。
我只需要在执行期间访问 jar 中的 xml 文件。我所说的访问是指 jar 文件中 xml 文件的正确文件路径,不需要文件内容。
最佳答案
问题出在这里:
StreamResult result = new StreamResult(new File(filePath));
您似乎已经知道,URL 不是文件路径,您不能将其视为文件路径。您根本无法执行 new File(filePath) 并期望它能够正常工作。您存储在 filePath
中的字符串根本不是文件路径,而是 URL。
但是您有一个更根本的问题:资源是只读的。你不能写信给它,期间。所有 Java 应用程序都部署在 .jar 或 .war 文件中,即使您可以访问原始存档(并且不保证可以),您也可能没有写入它的权限(特别是在 Windows 中,它很可能被锁定) ),即使您可以编写它,应用程序也不会看到更改。
简而言之,您不应该尝试写入资源。
相反,将您的资源视为默认值集,并选择一个可靠的位置(例如临时文件或用户主目录中的文件)来写入新数据:
File resultFile = File.createTempFile("history", ".xml");
StreamResult result = new StreamResult(resultFile);
旁注:始终公开捕获异常的堆栈跟踪,无论是使用日志记录语句、异常链接,还是至少调用 printStackTrace()。另外,不要捕获 java.lang.Exception;您不应该抑制程序员错误,例如 NullPointerException、IndexOutOfBoundsException、IllegalArgumentException 等。相反,只捕获需要捕获的异常:
} catch (ParserConfigurationException | SAXException | IOException | TransformerException ex) {
关于Java Swing 将变量分配给 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47715992/