public void writeXmlFile(){
String fileName = "abc.xml";
String configPath = getClass().getResource( "/" ).getPath();
StringBuilder filepath = new StringBuilder(30);
filepath.append(configPath).append("/").append(fileName);
File file = new File(filepath.toString());
if(!file.isFile()){//所读取的文件不存在,那么就创建一个新的文件
try {
if(file.createNewFile()){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=null;
try{
builder = dbf.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement("ABC");
doc.appendChild(root); //将根元素添加到文档上
FileOutputStream fos = new FileOutputStream(new File(filepath.toString()));
OutputStreamWriter outwriter = new OutputStreamWriter(fos,"UTF-8");
callWriteXmlFile(doc,outwriter,"UTF-8");
outwriter.close();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void callWriteXmlFile(Document doc, Writer w,String encoding) {
try {
Transformer xformer = TransformerFactory.newInstance().newTransformer();
DOMSource source = new DOMSource(doc);
xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(w);
xformer.transform(source, result);
}catch (TransformerConfigurationException e) {
e.printStackTrace();
}catch (TransformerException e) {
e.printStackTrace();
}
}
无论是xml文件还是内容都是UTF-8编码格式,搞定收工!