java - 写入文本文件时,未写入大约 4,000 个值

标签 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;
}

最佳答案

我建议您在处理结束时关闭 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(); 
}

关于java - 写入文本文件时,未写入大约 4,000 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26903549/

相关文章:

java - 从 RecyclerView Adapter 类保存 CheckBox 状态

java - 使用JAVA解析SOAP响应并提取特定节点

android - 带有 BottomNavigationView 的 FloatingActionButton

xml - 查询字符串中不区分大小写的xpath 1.0

xml - 将 UTF8 数据导出到 Excel 的最佳方法是什么?

java - 我将不同的类放在 ArrayList 中,我想访问我的类的方法

java - Android 空 ArrayList 和 Spinner

java - 无法 Autowiring 字段 spring-boot

java - 尝试使框架从 Action 监听器中消失

android - 将 arraylist<String> 值插入到 android 中的 sqlite