我正在尝试读取XML文件并重新编写它:
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
FileInputStream inputstream = new FileInputStream(dat3);
Document doc = docBuilder.parse(inputstream);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(dat3).getAbsolutePath());
transformer.transform(source, result);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
但它似乎不起作用,因为我认为写作和阅读存在冲突:
transformer.transform(source,result); 删除结果java.io.FileNotFoundException:拒绝访问
答案 0 :(得分:0)
您的代码正常运行。我试试这个样本。
public class Tester {
private static String dat3 = "data/xml";
public static void main(String[] args) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
FileInputStream inputstream = new FileInputStream(dat3);
Document doc = docBuilder.parse(inputstream);
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(
new File(dat3).getAbsolutePath());
transformer.transform(source, result);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}
查看dat3文件权限。