有效地将XML转换为JSON的大量文件

时间:2018-08-22 03:31:37

标签: java xml

我有几个XML文件(大小为GBs)要转换为JSON。我可以轻松地使用JSON库(org.json-https://mvnrepository.com/artifact/org.json/json/20180813)转换小型文件(以KiloBytes为单位)。

这是我正在使用的代码

            static String line="",str="";
            BufferedReader br = new BufferedReader(new FileReader(link));
            FileWriter fw = new FileWriter(outputlink);
            JSONObject jsondata = null;

            while ((line = br.readLine()) != null) 
            {   
                str+=line;  
            }
            jsondata = XML.toJSONObject(str);

但是大文件(甚至<100 MB的文件)的处理时间太长,而大文件则抛出java.lang.OutOfMemoryError:Java堆空间。因此,如何优化代码以处理大文件(或任何其他方法/库)。

更新

我已更新代码,并将XML逐段写入

我的XML:

<PubmedArticleSet>
     <PubmedArticle>
     </PubmedArticle>
     <PubmedArticle>
     </PubmedArticle>
...
</PubmedArticleSet>

因此,我忽略了根节点<PubmedArticleSet>(稍后将添加)将每个<PubmedArticle> </PubmedArticle>转换为JSON并一次写入

         br = new BufferedReader(new FileReader(link));
         fw = new FileWriter(outputlink,true);
         StringBuilder str = new StringBuilder();
         br.readLine(); // to skip the first three lines and the root 
         br.readLine();
         br.readLine();

         while ((line = br.readLine()) != null) {


            JSONObject jsondata = null;

            str.append(line);
            System.out.println(str);
            if (line.trim().equals("</PubmedArticle>")) { // split here


                jsondata = XML.toJSONObject(str.toString());

                String jsonPrettyPrintString = jsondata.toString(PRETTY_PRINT_INDENT_FACTOR);
                fw.append(jsonPrettyPrintString.toString());

                System.out.println("One done"); // One section done
                str= new StringBuilder();


            }
           }
            fw.close();

我不再遇到HeapError了,但是对于300 MB范围的文件来说,处理仍然要花费数小时。请提供任何建议以加快此过程。

2 个答案:

答案 0 :(得分:3)

此陈述是影响您表现的主要原因:

str+=line;

这导致许多String对象的分配,复制和取消分配。

您需要使用StringBuilder

StringBuilder builder = new StringBuilder();
while ( ... ) {
    builder.append(line);
}

以较大的块而不是逐行读取文件也可能(在较小程度上)帮助

答案 1 :(得分:0)

读取大文件的IO操作非常耗时。尝试利用一个库来为您处理。例如使用apache commons IO

File xmlFile= new File("D:\\path\\file.xml");
String xmlStr= FileUtils.readFileToString(xmlFile, "UTF-8");
JSONObject xmlJson = XML.toJSONObject(xmlStr);