java对象转化为流,如何将大型XML文件转换为对象的流式Java8

Hy,

I have a (very)large XML file (100GB) with a list of foo, I want to convert-it into a stream like they where introduce into java 8 of object:

Any idea of lib or code sample?

at the beginning:

...

...

at the end:

Stream foosStream = ????("foo.xml")

streamFoos.forEach(foo->foo.doFooStuffs());

Edit:

@Pierre Thank-you, here is the implementation of your solution:

try {

XMLEventReader reader = XMLInputFactory.newInstance().

createXMLEventReader(stream);

final Unmarshaller unmarshaller = JAXBContext.newInstance(XXXXX.class).createUnmarshaller();

Iterator it = new XmlIterator<>(reader, unmarshaller, "xxxxxx");

return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.ORDERED), false);

} catch (XMLStreamException e1) {

logger.error("XMLStreamException", e1);

} catch (JAXBException e) {

logger.error("JAXBException", e);

}

and

public class XmlIterator implements Iterator {

private final Logger logger = LoggerFactory.getLogger(this.getClass());

XMLEventReader reader;

XMLEvent event;

Unmarshaller unmarshaller;

String name;

public XmlIterator(XMLEventReader reader, Unmarshaller unmarshaller, String name) {

this.reader = reader;

this.unmarshaller = unmarshaller;

this.name = name;

try {

reader.next();

this.event = reader.peek();

} catch (XMLStreamException e) {

logger.error("", e);

event = null;

}

}

@Override

public boolean hasNext() {

try {

while (event != null && !(event.isStartElement() && name.equals(event.asStartElement().getName().getLocalPart()))) {

Object a = reader.next();

event = reader.peek();

}

return event != null;

} catch (XMLStreamException e) {

logger.error("", e);

event = null;

}

return event != null;

}

@Override

public T next() {

try {

T next = ((JAXBElement) unmarshaller.unmarshal(reader)).getValue();

event = reader.peek();

return next;

} catch (JAXBException e) {

logger.error("error during unmarshalling ", e);

return null;

} catch (XMLStreamException e) {

logger.error("error during stream ", e);

return null;

}

}

}

解决方案

Each time you see a tag 'foo' (using https://docs.oracle.com/javase/7/docs/api/javax/xml/stream/XMLEventReader.html#peek() ) , use the Stax reader to parse and build your object Foo

Foo readFoo(XMLEventReader xmlIn) throws XMLStreamException {

(...)

return foo;

}

implements a java.util.Iterator that will use the previous function to return the 'next()' Foo

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值