让我重新表述一下我的问题。我正在文件中搜索一些关键字。当我喜欢它时,我需要在这个关键字之前打印一些行,包括它
我想打印以一些关键字开头的行范围
line1
line2
someword
line4
line5
找到这个关键词后,我需要打印第1行第2行和这个关键词。知道吗?
我想我理解这个问题了。采用行分隔输入,逐行搜索关键字。如果找到关键字,请打印前面的n行,然后再打印关键字。
final String input = "line1nline2nsomewordnline4nline5";
int numberOfLinesToDisplay = 2;
String keyword = "someword";
// Split on the newline character
String[] lines = input.split("n");
// Loop over each line
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
// Checking for the keyword...
if (keyword.equals(line)) {
// Reverse the for loop to print "forwards"
for (int j = numberOfLinesToDisplay; j >= 0; j--) {
// Make sure there is something there
if (i - j >= 0) {
// Simply print it
System.out.println(lines[i - j]);
}
}
}
}
我相信还有更优雅的解决方案,但这适用于所描述的情况。
编辑:要读取文件,假设性能不是一个紧迫的问题,你可以使用这样的东西:(未测试!)
String keyword = "someword";
int numberOfLinesToDisplay = 2;
List<String> list = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(myFile));
int i = 0;
// Loop over each line
String line;
while ((line = br.readLine()) != null) {
// Add the line to the list
list.add(line);
// Checking for the keyword...
if (keyword.equals(line.trim())) {
// Reverse the for loop to print "forwards"
for (int j = numberOfLinesToDisplay; j >= 0; j--) {
// Make sure there is something there
if (i - j >= 0) {
// Simply print it
System.out.println(list.get(i - j));
}
}
}
i++;
}
第2版:添加了trim()
以删除多余的空白。
我刚刚更新了@starr创建的上一个示例及其工作。我添加了"indexof"elemet来查找我的字符串。非常感谢您的帮助!
try {
String keyword = "!!!";
int numberOfLinesToDisplay = 8;
ArrayList<String> list = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("C:\some.log"));
int i = 0;
// Loop over each line
String line;
while ((line = br.readLine()) != null) {
// Add the line to the list
list.add(line);
// Checking for the keyword...
int indexfound = line.indexOf(keyword);
// If greater than -1, means we found the word
if (indexfound > -1) {
// Reverse the for loop to print "forwards"
for (int j = numberOfLinesToDisplay; j >= 0; j--) {
// Make sure there is something there
if (i - j >= 0) {
// Simply print it
System.out.println(list.get(i - j));
}
}
}
i++;
}
}catch (IOException ie){
System.out.println("File not found");
}