我正在编写一个类,它会在更新时读取日志文件中的行。
我正在使用Apache VFS2来获取更新文件时调用的方法。我的主要问题是如果线路尚未完成,我不想从文件中读取该行,因为它在末尾有一个“\ n”或“\ r”行分隔符类型字符。我想我已经查看了所有可以读取行的Java库,但它们都丢弃了EOF和行终止信息,所以我认为我不能使用它们。
相反,我正在逐字节地读取它,然后检查结果然后丢弃在最后一行分隔符之后的所有内容。我想知道你们对于这样做的最好方法的想法是什么。
例如:
2013-Jul-01_14:07:17.875 - Connection to Message Bus is reestablished<LF>
2013-Jul-01_14:07:17.875 - Connection to Message Bus is reestablished<LF>
2013-Jul-01_14:15:08.205 - No connection to Message Bus - reestablish before we can publish<LF>
2013-Jul-01_14:15:08.205 - NOT A REAL LINE PLEASE DONT READ
我想读取前3个而不是第4个,因为它没有换行符或回车符()。
我看过Apache commons-io Tailer的东西,但我不知道这是否会给我“不完整”的行(我意识到我将不得不抛弃VFS2的东西来使用它)。
所以psudo-code:
private void ingestFileObject(FileObject file) {
BufferedInputStream bs = new BufferedInputStream(file.getContent().getInputStream());
StringBuilder result = new StringBuilder();
while (bs.available() > 0) {
result.append((char) bs.read());
}
bs.close();
String resultString = result.toString();
//determine what part of resultString is after last carriage return/line seperate (using regex [\\r\\n]+?
//remove the offending part of String.
}
此外,欢迎完全忽略我的psudo代码的任何其他解决方案......
由于
答案 0 :(得分:1)
正在使用Scanner
为您提供帮助吗?
Scanner scanner = new Scanner(file);
//block till there is some thing with a new line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//do processing.
}
答案 1 :(得分:1)
这就是我最终做的事情:
BufferedReader bufReader = new BufferedReader(new InputStreamReader(file.getContent().getInputStream()));
StringBuilder result = new StringBuilder();
int readInInt = -1;
String charsSinceLastLineSep = "";
if (bufReader.ready()) {
while (-1 != (readInInt = bufReader.read())) {
char readInChar = (char) readInInt;
// if new line reset line buffer, otherwise add to buffer
if (readInChar == '\n' || readInChar == '\r') {
charsSinceLastLineSep = "";
} else {
charsSinceLastLineSep += readInChar;
}
result.append(readInChar);
}
bufReader.close();
// remove all characters added since last Carriage Return or NewLine was found indicating
// that line was not a complete log line
String resultString = (result.subSequence(0, (result.length() - charsSinceLastLineSep.length())).toString());