Search code examples
javabufferedreaderfile-read

read the html file in java


In java i have to read multiple files to search some text . Files are containing large html data so its difficult to read the content of the html file with the help of following code . Is any direct method to fetch the content of a file using java . I am using the following code but its making my application slow suggest me the best alternate of it

try{
   FileReader fr=new FileReader("path of the html file");
   BufferedReader br= new BufferedReader(fr);
    String content="";
   while((s=br.readLine())!=null)
    {

     content=content+s;

    } 

     System.out.println("content is"+content);
   }
  catch(Exception ex)
   {

    }

Solution

  • String concatenation is always slow when done in a loop

    You will need to change it to using a StringbBuilder and giving that StringBuilder a decent starting size.

    FileReader fr=new FileReader("path of the html file");
    BufferedReader br= new BufferedReader(fr);
    StringBuilder content=new StringBuilder(1024);
    while((s=br.readLine())!=null)
        {
        content.append(s);
        }