Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中将大型XML转换为字符串_Java_Xml_Apache Pig_Dom4j - Fatal编程技术网

如何在java中将大型XML转换为字符串

如何在java中将大型XML转换为字符串,java,xml,apache-pig,dom4j,Java,Xml,Apache Pig,Dom4j,作为PIG脚本的一部分,我需要获取使用UDF生成的XML,而XML太大(大约1.5GB)。目前我正在使用下面的代码将XML转换为字符串 StringWriter sw = new StringWriter(); XMLWriter output = new XMLWriter(sw, xmlFormat); try { output.write(document); output.close(); } catch (IOExcepti

作为PIG脚本的一部分,我需要获取使用UDF生成的XML,而XML太大(大约1.5GB)。目前我正在使用下面的代码将XML转换为字符串

    StringWriter sw = new StringWriter();
    XMLWriter output = new XMLWriter(sw, xmlFormat);
    try {
       output.write(document);
        output.close();
    } catch (IOException e) {}

    return sw.toString();
这会抛出OutofMemoryError,因为StringWriter在内部使用字符串缓冲区,并且它依赖于数组。因为数组使用整数作为索引,并且XML的长度超出了int范围

有没有办法将这个大xml转换成字符串并发送回pig脚本?或者我们可以通过任何其他方式实现它

仅供参考-我们正在使用dom4j(
org.dom4j.Document
)来处理XML

更新1: 我尝试了下面的代码,我现在能够存储800MB,但仍然是1.5GB的文件失败

    ByteArrayOutputStream result = new ByteArrayOutputStream();
    try {
        XMLWriter output = new XMLWriter(result, xmlFormat);
        output.write(document);
        output.close();
        return result.toString("UTF-8");
    } catch (IOException e) {}

为了避免内存不足,您需要对xml文件进行流式处理。您可以使用该流并直接在Pig脚本中解析xml。

AFAIK xml已经是基于文本的格式,因此它实际上已经是一个字符串。我也不知道你为什么要把它转换成字符串,也许问题在于你的推理。在任何情况下,您都可以:1)为JVM分配更多内存,或2)使用文件而不是字符串进行传输,然后在另一端读取。