2012-11-08 42 views
0

在java中,我必须读取多个文件才能搜索某些文本。文件包含大量html数据,因此在下面的代码帮助下很难阅读html文件的内容。 是使用java获取文件内容的直接方法。我使用下面的代码,但它使我的应用缓慢表明我它的最佳替换在一个循环完成后阅读java中的html文件

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) 
    { 

    } 
+0

可以使用http://htmlparser.sourceforge.net/ – Abubakkar

+0

@adesh请为什么原因是有Swing和AWT标签 – mKorbel

回答

4

字符串连接总是慢

您需要将其更改为使用StringbBuilder并给这个StringBuilder一个体面的开始大小。

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); 
    } 
+0

这是什么1024 – adesh

+0

为建设者的默认大小。这个大小被用作分配的开始大小,一旦你的字符串变得比你的起始大小更大,那么构建器将会增加其内部大小的两倍,并且这样做必须创建一个新的内部数组。为了避免大量的unneccasery copiing选择它足够高,1024是一个猜测,如果你知道你通常会阅读1000000字符的HTML,你可以指定它为新的StringBuilder(1000000); – Peter