使用 DocumentBuilder 解析 InputStreamReader
我对 Java 的经验很少。我试图强制将文档读取为 UTF-8,但在尝试将 InputStream 阅读器连接到文档生成器时遇到了困难。
到目前为止,这是我所得到的:
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
if( pathToFile == null ) throw new Exception("You must supply a pathToFile parameter");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputStreamReader in = new InputStreamReader( new FileInputStream( pathToFile ), "utf-8" );
BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) );
Element records = builder.parse(reader).getDocumentElement();
如果有人能为我提供一些指示,我将不胜感激
I've very little Java experience. I'm trying to force a document to be read as UTF-8, but have come stuck trying to hook the InputStream reader to the document builder.
Here's what I have so far:
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
if( pathToFile == null ) throw new Exception("You must supply a pathToFile parameter");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputStreamReader in = new InputStreamReader( new FileInputStream( pathToFile ), "utf-8" );
BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) );
Element records = builder.parse(reader).getDocumentElement();
Be grateful if someone can provide me with some pointers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要将
InputStreamReader
包裹在InputStreamReader
周围。 (编辑此外,由于没有方法从 Reader 解析 XML,因此您需要将 reader 包装在 InputSource):Don't wrap an
InputStreamReader
around yourInputStreamReader
. (EDIT Also, since there's no method to parse XML from a Reader, you need to wrap the reader in an InputSource):假设这是 Groovy,您可以摆脱很多 Java 的麻烦:
没有尝试过,但是:
应该可以...
Assuming this is Groovy, you can rid yourself of a lot of the Java cruft:
Not tried it, but:
should work...