在您阅读文件以查找您的唯一 ID 时,请保留对documentRequestMessage
您遇到的最新 ID 的引用。当您找到唯一 ID 时,您将拥有提取消息所需的参考。
在这种情况下,“参考”可能意味着几件事。由于您没有遍历 DOM(因为它不是有效的 XML),您可能只会将位置存储在文件中documentRequestMessage
。如果您使用的是FileInputStream
(或任何支持的InputStream
地方mark
),您可以只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 */
}
}
}
}