您所要求的只是编写和读取作为独立java类的文件。但是你去了像spring-mvc这样的项目,我无法写或更新价值。
我使用File sequenceStorageFile = ResourceUtils.getFile("classpath:sequenceValue/sequence.xml");
从此xml文件中读取数据。但我不知道如何写入同一个文件来更新值。
有人可以告诉我如何写入相同的xml文件吗?
答案 0 :(得分:0)
检查以下示例
try {
String filepath = "c:\\file.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
node = doc.getFirstChild();
Node nodecon = doc.getElementsByTagName("TAGNAME").item(0);
NamedNodeMap attr = nodecon.getAttributes();
Node nodeAttr = attr.getNamedItem("ID");
nodeAttr.setTextContent("2");
Element age = doc.createElement("ATTRIBUTE_NAME");
age.appendChild(doc.createTextNode("NEW_ATTRIBUTE_VALUE"));
nodecon.appendChild(age);
NodeList list = nodecon.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if ("UPDATE_NODE_NAME".equals(node.getNodeName())) {
node.setTextContent("NEW_NODE_VALUE");
}
}
// write the content into xml file
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 (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
答案 1 :(得分:0)
不应该这样做,可以使用资源“文件”作为只读模板(它可能在密封的jar中)来创建文件,例如在System.getProperty(“user.home”)目录中
InputStream in = getClass().getResourceAsStream("/sequenceValue/sequence.xml");
Path seqPath = Paths.get(System.getProperty("user.home"), "seq.xml");
Files.copy(in, path);