java - how to print output in a text file -


i'm trying read text file, operation , output result in different file reason prints 1 line of results.

    scanner file = new scanner(new fileinputstream("/.../file.txt"));     printwriter p = new printwriter(new filewriter("/.../output.txt"));      int count = 0;      while (file.hasnextline())      {         string s = file.nextline();         count++;          try         {             if(s.contains("#avfc")){                 p.printf("there %d words on line ", s.split("\\s").length-1);                 p.println(count);                 p.close();              }         }         catch(exception ex){              ex.printstacktrace();          }         }     file.close(); 

this output;

there 4 words on line 1 

but output should be:

there 4 words on line 1  there 10 words on line 13  there 8 words on line 16 

why close p in while loop?

scanner file = new scanner(new fileinputstream("/.../file.txt")); printwriter p = new printwriter(new filewriter("/.../output.txt"));  int count = 0;  while (file.hasnextline())  {     string s = file.nextline();     count++;      try     {         if(s.contains("#avfc")){             p.printf("there %d words on line ", s.split("\\s").length-1);             p.println(count);          }     }     catch(exception ex){          ex.printstacktrace();      }     }  p.close(); file.close(); 

in code printwriter closed on first match found in file , other matches not write in output file because closed file writer before.


Comments

Popular posts from this blog

visual studio - vb.net filter binding source by time -

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -