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

	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编码格式,搞定收工!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值