如何阅读上面和下面的java中的特定linenumber的行? [英] How to read lines above and below a particular linenumber in java?

查看:446
本文介绍了如何阅读上面和下面的java中的特定linenumber的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆