【问题标题】:Java, how to extract some text from a large file and import it into a smaller fileJava,如何从大文件中提取一些文本并将其导入到较小的文件中
【发布时间】:2013-05-29 12:03:23
【问题描述】:

我对 Java 编程比较陌生,正在尝试创建一个可以帮助一些同事的应用程序。

我正在尝试做的背景是,读取一个大文件的内容,最多可能超过 400,000 行,其中包含 XML 但不是有效的 XML 文档,就像它的一种日志一样。

我正在尝试做的是构建一个应用程序,用户在其中输入唯一 ID,然后扫描文档以查找它是否存在,如果存在,并且通常唯一 ID 在生成的 XML 中出现几次,然后我想向后遍历到节点 ID <documentRequestMessage> ,然后将该节点中的所有内容复制到其关闭节点,并将其放入它自己的文档中。

我知道如何创建新文档,但我正在努力找出如何从本质上“向后查找”并将所有内容复制到结束标记,非常感谢任何帮助。

编辑

不幸的是,到目前为止,我还无法弄清楚如何实施这 3 条建议中的任何一条。

correlationId 是前面提到的唯一引用。

我拥有的当前代码,它可以工作并将结果输出到控制台,是

String correlationId = correlationID.getText();
BufferedReader bf = new BufferedReader(new FileReader(f));
System.out.println("Looking for " + correlationId);
int lineCount = 0;
String line;

while ((line = bf.readLine()) != null) {
    lineCount++;
    int indexFound = line.indexOf(correlationId);

    if (indexFound > -1) {
        System.out.println("Found CorrelationID on line " + "\t" + lineCount + "\t" + line);
    }
}

bf.close();

非常感谢任何进一步的帮助,我不是要求有人为我写,只是一些非常清晰和基本的说明:) 请

编辑 2

可以在here找到我正在尝试读取和提取的文件的副本

【问题讨论】:

  • 问题 - 你怎么知道它不是有效的 XML?你能发布一个关于它“无效”的样本吗?
  • @SeanBright 我知道它不是有效的 XML 的原因是因为 1) XMLSpy 不会验证它。 2)它包含多个 (585 个条目)! 3) 另外还有我认为不是正确的 XML cmets 的 cmets,例如 [2013-05-29 12:18:57,626] 默认值:4''# DocumentCompositionLogger sca.component.mediation.java.Custom1322734159344 INFO - requestDocumentProductionPackG02 请求有效负载收到>>>>>> 我已将文件复制到此处,以便您可以查看我正在阅读的整个文档,可以在 here 找到
  • @Gilbert 的建议看起来很简单,你能说说你在实现它时遇到了什么麻烦吗?

标签: java xml text io


【解决方案1】:

在您阅读文件以查找您的唯一 ID 时,请保留对您遇到的最新 documentRequestMessage 的引用。找到唯一 ID 后,您就已经有了提取消息所需的参考。

在这种情况下,“参考”可能意味着几件事。由于您没有遍历 DOM(因为它不是有效的 XML),您可能只会将位置存储在 documentRequestMessage 所在的文件中。如果您使用的是FileInputStream(或任何支持markInputStream),您可以只使用mark/reset 来存储并返回到文件中您的消息开始的位置。

这是我相信您正在寻找的实现。它根据您链接的日志文件做出了很多假设,但它适用于示例文件:

private static void processMessages(File file, String correlationId)
{
    BufferedReader reader = null;

    try {
        boolean capture = false;
        StringBuilder buffer = new StringBuilder();
        String lastDRM = null;
        String line;

        reader = new BufferedReader(new FileReader(file));

        while ((line = reader.readLine()) != null) {
            String trimmed = line.trim();

            // Blank lines are boring
            if (trimmed.length() == 0) {
                continue;
            }

            // We only actively look for lines that start with an open
            // bracket (after trimming)
            if (trimmed.startsWith("[")) {
                // Do some house keeping - if we have data in our buffer, we
                // should check it to see if we are interested in it
                if (buffer.length() > 0) {
                    String message = buffer.toString();

                    // Something to note here... at this point you could
                    // create a legitimate DOM Document from 'message' if
                    // you wanted to

                    if (message.contains("documentRequestMessage")) {
                        // If the message contains 'documentRequestMessage'
                        // then we save it for later reference
                        lastDRM = message;
                    } else if (message.contains(correlationId)) {
                        // If the message contains the correlationId we are
                        // after, then print out the last message with the
                        // documentRequestMessage that we found, or an error
                        // if we never saw one.
                        if (lastDRM == null) {
                            System.out.println(
                                    "No documentRequestMessage found");
                        } else {
                            System.out.println(lastDRM);
                        }

                        // In either case, we're done here
                        break;
                    }

                    buffer.setLength(0);
                    capture = false;
                }

                // Based on the log file, the only interesting messages are
                // the ones that are DEBUG
                if (trimmed.contains("DEBUG")) {
                    // Some of the debug messages have the XML declaration
                    // on the same line, and some the line after, so let's
                    // figure out which is which...
                    if (trimmed.endsWith("?>")) {
                        buffer.append(
                                trimmed.substring(
                                    trimmed.indexOf("<?")));
                        buffer.append("\n");
                        capture = true;
                    } else if (trimmed.endsWith("Message:")) {
                        capture = true;
                    } else {
                        System.err.println("Can't handle line: " + trimmed);
                    }
                }
            } else {
                if (capture) {
                    buffer.append(line).append("\n");
                }
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace(System.err);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ex) {
                /* Ignore */
            }
        }
    }
}

【讨论】:

  • 根据您的 cmets 更新。
【解决方案2】:

您可以做的是读取文件的内容并查找&lt;documentRequestMessage&gt; 元素。当您找到上述元素之一时,请阅读直到找到 &lt;/documentRequestMessage&gt; 并将其存储在列表中,以便所有 documentRequestMessage 将在列表中可用。

您可以在最后或添加到列表时遍历此列表以查找您正在寻找的唯一 ID。如果您发现它写入 XML 文件或忽略它。

【讨论】:

    【解决方案3】:

    我假设您的日志是一系列 &lt;documentRequestMessage&gt; 内容。

    根本不扫描日志。

    阅读日志,每次遇到&lt;documentRequestMessage&gt; 标头时,开始将&lt;documentRequestMessage&gt; 块的内容保存到块区域中。

    我不确定您是否必须解析 XML,或者您可以将其保存为字符串列表。

    当您遇到&lt;/documentRequestMessage&gt; 预告片时,请检查该块的 ID 是否与您要查找的 ID 匹配,

    如果 ID 匹配,则将 &lt;documentRequestMessage&gt; 块写入输出文件。如果 ID 不匹配,则清除块区域并读取到下一个 &lt;documentRequestMessage&gt; 标头。

    这样,你的文件读取就没有回溯了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      相关资源
      最近更新 更多