如何读取java中特定行号上方和下方的行?
我需要解析 txt 格式的日志文件。
我需要匹配字符串并读取匹配字符串的上方和下方行。
我需要执行类似于 grep -A 30 -B 50 'hello' 的操作。
如果您有任何其他建议,欢迎您这样做。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
逐行读取文件,并匹配您的字符串(正则表达式或 String.indexOf(""))。将前 n 行保留在内存中,以便在匹配字符串时可以打印它们。使用 BuffereReader.readLine( ) 逐行读取文件(请注意,使用 BufferedReader 实际上更复杂,因为无法跳回)。
或者为了获得更大的灵活性RandomAccessFile。使用此方法,您可以标记您的位置,打印接下来的 m 行,然后跳回从上次离开的位置继续搜索。
Read the file line by line, and match your string (either regexp or String.indexOf("")). Keep the previous n lines in memory so when you've matched your string you can print them. Use BuffereReader.readLine() to read the file line by line (note that using the BufferedReader is actually more complicated because you cannot jump back).
Or for more flexibility RandomAccessFile. With this method you can mark your position, print the next m lines and then jump back to continue your search from where you left it.
伪代码:
您可以使用 BufferedReader 逐行读取文件,Pattern 根据正则表达式检查该行,以及 队列 存储之前的行。
pseudocode:
You can use BufferedReader to read a file line by line, Pattern to check the line against a regular expression, and Queue to store previous lines.
您可以使用以下代码(使用 java 5 api java.util.Scanner):
您可能需要添加额外的检查来检查
prev
不为 null 并调用scanner.hasNextLine()
在String next =scanner.nextLine()
之前You may use following code(uses java 5 api java.util.Scanner):
You may want to add additional checks for
prev
being not null and Callingscanner.hasNextLine()
beforeString next = scanner.nextLine()