写入文本文件时,不会写入大约4,000个值

时间:2014-11-13 07:31:38

标签: java xml arraylist

我一直在尝试解析一个XML文件,将我需要的每个节点存储到一个数组/ ArrayList中;我试过了两个。解析器能够获取我想要的每个值并将其存储到数组(列表)中。我甚至打印了之后的长度,它正好是262,144个值(512 * 512)。但是,一旦我尝试将此数组打印到文本文件,它总是会丢失大约3800个值。我已经尝试了很多工作来实现这一点,但无论我尝试存储多少值(即使在尝试只有大约147,000个值的XML时),它仍然会留下大约4000个值。这是我的解析器/编写器。

public class Reader 
{
private String path;

public static void main(String[] args)
{
    Document xmlDoc = getDocument("./src/porc.tmx");

    String fileName = "out.txt";
    String[] array = new String[262144];
    try
    {
        NodeList gidList = xmlDoc.getElementsByTagName("tile");
        for(int i = 0; i < gidList.getLength(); i++)
        {
            Node g = gidList.item(i);
            if(g.getNodeType() == Node.ELEMENT_NODE)
            {
                Element gid = (Element) g;
                String id = gid.getAttribute("gid");
                array[i]=id;
            }
        }

        PrintWriter outputStream = new PrintWriter(fileName);
        for(int j = 0; j < 262144; j++)
        {
            outputStream.println(array[j]);
        }
    }

    catch(Exception e)
    {
        e.printStackTrace();
    }
}

private static Document getDocument(String docString)
{
    try
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);
        factory.setValidating(false);

        DocumentBuilder builder = factory.newDocumentBuilder();

        return builder.parse(new InputSource(docString));
    }

    catch(Exception ex)
    {
        System.out.println(ex.getMessage());
    }

    return null;
}

1 个答案:

答案 0 :(得分:6)

我建议您在处理结束时关闭outputStream

PrintWriter outputStream = null;
try
{
    NodeList gidList = xmlDoc.getElementsByTagName("tile");
    for(int i = 0; i < gidList.getLength(); i++)
    {
        Node g = gidList.item(i);
        if(g.getNodeType() == Node.ELEMENT_NODE)
        {
            Element gid = (Element) g;
            String id = gid.getAttribute("gid");
            array[i]=id;
        }
    }

    outputStream = new PrintWriter(fileName);
    for(int j = 0; j < 262144; j++)
    {
        outputStream.println(array[j]);
    }
}

catch(Exception e)
{
    e.printStackTrace();
}
finally
{
    if (outputStream != null)
        outputStream.close(); 
}