title: Java Scanner to print previous and next lines
body: <p>I am using 'java.util.Scanner' to read and scan for keywords and want to print the previous 5 lines and next 5 lines of the encountered keyword, below is my code</p>
  
  <pre><code> ArrayList&lt;String&gt; keywords = new ArrayList&lt;String&gt;();      
   keywords.add("ERROR");             
   keywords.add("EXCEPTION");
   java.io.File file = new java.io.File(LOG_FILE);
        Scanner input = null;
      try {
          input = new Scanner(file);
      } catch (FileNotFoundException e) {         
          e.printStackTrace();
      }
        int count = 0;
        String previousLine = null;
        while(input.hasNext()){
            String line = input.nextLine();
            for(String keyword : keywords){                
                if(line.contains(keyword)){                                             
                    //print prev 5 lines
                    system.out.println(previousLine); // this will print only last previous line ( i need last 5 previous lines)
                    ???
                    //print next 5 lines                    
                    system.out.println(input.nextLine());
                    system.out.println(input.nextLine());
                    system.out.println(input.nextLine());
                    system.out.println(input.nextLine());
                    system.out.println(input.nextLine());
                }
                previousLine = line;
            }
  </code></pre>
  
  <p>any pointers to print previous 5 lines..?</p>