java 读utf-8 xml_在Java中如何读取UTF-8格式的XML文件 - How to read UTF-8 XML file in Java

在使用JAXB解析XML时遇到UTF-8编码异常,通过将InputStream转换为UTF-8的Reader并设置InputSource编码为UTF-8,解决了异常。优化后的代码增加了泛型支持。
摘要由CSDN通过智能技术生成

在使用JAXB unmarshal XML的时候碰到了一个异常: Invalid byte 1 of 1-byte UTF-8 sequence

public static Object unmarshal(InputStream xml, Class> clazz) {

Object obj = null;

try {

JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());

Unmarshaller u = jc.createUnmarshaller();

obj = u.unmarshal(xml);

} catch (JAXBException e) {

throw new RuntimeException("Can't unmarshal this xml file, please check the error message: " + e.getMessage());

}

return obj;

}

问题出现在u.unmarshal(xml)这个地方,这句实际上调用的是SaxParser.parse()方法,这是一个encoding的问题,我们需要将输入流转换为UTF-8格式,然后再由SaxParser去解析该输入流, 解决方法如下:

public static Object unmarshal(InputStream xml, Class> clazz) {

Object obj = null;

try {

JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());

Unmarshaller u = jc.createUnmarshaller();

Reader reader = new InputStreamReader(xml,"UTF-8");

InputSource is = new InputSource(reader);

is.setEncoding("UTF-8");

obj = u.unmarshal(is);

} catch (JAXBException e) {

throw new RuntimeException("Can't unmarshal this xml file, please check the error message: " + e.getMessage());

} catch (UnsupportedEncodingException e) {

throw new RuntimeException("Doesn't support encoding: UTF-8, please check the error message: " + e.getMessage());

}

return obj;

}

下面将使用泛型进一步优化该方法:

public static T unmarshal(InputStream xml, Class clazz) {

T obj = null;

try {

JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());

Unmarshaller u = jc.createUnmarshaller();

Reader reader = new InputStreamReader(xml,"UTF-8");

Source source = new StreamSource(reader);

JAXBElement element = u.unmarshal(source, clazz);

obj = element.getValue();

} catch (JAXBException e) {

throw new RuntimeException("Can't unmarshal this xml file, please check the error message: " + e.getMessage());

} catch (UnsupportedEncodingException e) {

throw new RuntimeException("Doesn't support encoding: UTF-8, please check the error message: " + e.getMessage());

}

return obj;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值