如何显示文件中特定行的最后3行和后3行

时间:2017-10-07 19:03:45

标签: java file

我有一个看起来像这样的文本文件:

 technology
 education 
 medicine 
 women 
 architecture 
 programming 
 reading 
 coffee
 dog 
 cat 
 bird

我需要在此文件中搜索特定单词(例如' architecture')并获取前三行和接下来的三行。在上面的文件中,输出将是'教育医学女性'对于前三行和编程阅读咖啡'接下来的三行。

我能够获得接下来的三行,但是,我无法弄清楚如何在Java中获得前三行。你能帮帮我吗?这就是我到目前为止所做的:

 Scanner in = new Scanner(new File(filename));
       while (in.hasNextLine()){
          String str = in.nextLine();
            if (str.indexOf("architecture") !=-1){
             //this is where I need the code for getting the previous three 
             //lines to go

          }
       }

3 个答案:

答案 0 :(得分:0)

  • 从文件中读取所有行并将其存储在列表中
  • 找到您要查找的字符串的索引。
  • 以所需索引打印字符串。

    List<String> lines = Files.readAllLines(Paths.get(filename));
    int index = lines.indexOf("architect");
    String finalString = lines.get(index-3) + " " + lines.get(index-2) + " " + lines.get(index-1) + " " + lines.get(index+1) + " " + lines.get(index+2) + " " + lines.get(index+3);
    

答案 1 :(得分:0)

如果您想在architecture之后和之前使用单词,那么可能的解决方案之一是将所有单词存储到List并获取architecture的索引并得到-3和+3

List<String> lst = new LinkedList<>();
  int indx =0;
  int count =0;
  Scanner in = new Scanner(new File(filename));
       while (in.hasNextLine()){
          String str = in.nextLine();
          lst.add(str);
            if (str.indexOf("architecture") !=-1){
            indx=count;// get the index.
          }
        count++;
       }

现在,检索它们:

 //to avoid accessing out of bound index
 int max = (indx+3) >= count ? count -1 : (indx+3);//maximum index should be T-1.
 indx = (indx - 3) < 0 ? 0 : (indx - 3); // minimum index should be 0.

for(;indx <= max;indx++)
{
  System.out.println(lst.get(indx));
}

<强> >>>Demo<<<

答案 2 :(得分:0)

保留前3行。这是一个循环算法:一个数组,其中最旧的元素被覆盖。

 String[] previousLines = new String[3];
 int previousWritePos = 0;
 int previousCount = 0;

 Scanner in = new Scanner(new File(filename));
 while (in.hasNextLine()){
     String str = in.nextLine();
     if (str.indexOf("architecture") !=-1){
          //this is where I need the code for getting the previous three 
          //lines to go
     }

     // Remember this line as previous line:
     previousLines[previousWritePos] = str;
     if (previousCount < 3) {
         ++previousCount;
     }
     previousWritePos = (previousWritePos + 1) % 3;
 }

 for (int i = 0 ; i < previousCount; ++i) {
     int index = (previousWritePos + 2 - i) % 3;
     System.out.println("Previous: " + previousLines[index];
 }