`
zhwadezheng
  • 浏览: 7351 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

读取xml报 Invalid byte 1 of 1-byte UTF-8 sequence异常处理

    博客分类:
  • JAVA
 
阅读更多
	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编码格式,搞定收工!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics