简体   繁体   English

将InputStream对象转换为String的最佳方法

[英]Best way to convert an InputStream object to String

I have an InputStream object which contains several million file informations (Name, create date, author etc.) in XML format. 我有一个InputStream对象,其中包含XML格式的数百万个文件信息(名称,创建日期,作者等)。 I've already tried to convert it to String using IOUtils.copy method, but since the size of that information is pretty large it throws an java.lang.OutOfMemoryError , after running for few minutes. 我已经尝试使用IOUtils.copy方法将其转换为String ,但是由于该信息的大小很大,因此在运行几分钟后会抛出java.lang.OutOfMemoryError

Increasing JVM memory is not an option, since the number of files, which I collect info from, is increasing forever. 不能选择增加JVM内存,因为我从中收集信息的文件数量一直在增加。 So can someone suggest me what should I do to solve the issue? 那么有人可以建议我该怎么做才能解决这个问题?

The problem that you are having is the very reason stream based IO exists, it is simply not viable to slurp huge amounts of data into memory before consuming it. 您遇到的问题正是基于流的IO存在的原因 ,将大量数据消耗到内存之前根本就不可行。

Parse your stream as... a stream! 将您的流解析为...一个流! See the Oracle tutorials for more information on stream based XML parsing using SAX. 有关使用SAX进行基于流的XML解析的更多信息,请参见Oracle tutorials

XMLReader xmlreader =
    SAXParserFactory.newInstance().newSAXParser().getXMLReader();
xmlreader.setContentHandler(new ContentHandler() {
    ...
});

xmlreader.parse(new InputSource(myInputStream));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM