如何阅读上面和下面的java中的特定linenumber的行? [英] How to read lines above and below a particular linenumber in java?
问题描述
我需要解析 txt
格式的日志文件。
我需要匹配String并读取匹配的String的上下行。
我需要做类似于 grep -A 30 -B 50'hello'
。
如果您有任何其他建议,请不吝赐教。
可能会使用下面的代码(使用java 5 api java.util.Scanner):
$ p $ $ code>扫描器扫描器=新的扫描器(新的文件( YourFilePath));
String prev = null;
字符串current;
while(scanner.hasNextLine())
{
current = scanner.nextLine();
if(current.contains(YourRegEx))
break;
else
prev = current;
}
String next = scanner.nextLine();
您可能需要为 prev
不为空,在之前调用
scanner.hasNextLine()
字符串next = scanner.nextLine()
I need to parse a log file which is in txt
format.
I need to match the String and read above and below lines of the matched String.
I need to do something similar to grep -A 30 -B 50 'hello'
.
If You have any other suggestions to do it you are welcome.
You may use following code(uses java 5 api java.util.Scanner):
Scanner scanner = new Scanner(new File("YourFilePath"));
String prev = null;
String current;
while (scanner.hasNextLine())
{
current = scanner.nextLine();
if (current.contains("YourRegEx"))
break;
else
prev = current;
}
String next = scanner.nextLine();
You may want to add additional checks for prev
being not null and Calling scanner.hasNextLine()
before String next = scanner.nextLine()
这篇关于如何阅读上面和下面的java中的特定linenumber的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!