我想用一些关键字打印行范围
line1
line2
someword
line4
line5
找到此关键字后,我需要打印line1 line2和此关键字。 有什么想法吗?
答案 0 :(得分:0)
我想我理解这个问题。采用行分隔输入,逐行搜索关键字。如果找到关键字,则打印前面的n行,然后是关键字。
final String input = "line1\nline2\nsomeword\nline4\nline5";
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++;
}
Edit2:添加trim()
以删除额外的空格。
答案 1 :(得分:0)
我刚刚更新了@starf创建的上一个示例及其工作。我添加了“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");
}