Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中,从BufferedReader对象提取整个内容的最佳方法是什么?_Java_Performance_Bufferedreader - Fatal编程技术网

在Java中,从BufferedReader对象提取整个内容的最佳方法是什么?

在Java中,从BufferedReader对象提取整个内容的最佳方法是什么?,java,performance,bufferedreader,Java,Performance,Bufferedreader,我试图通过URL连接获取整个网页 最有效的方法是什么 我已经在这样做了: URL url = new URL("http://www.google.com/"); URLConnection connection; connection = url.openConnection(); InputStream in = connection.getInputStream(); BufferedReader bf = new BufferedReader(new InputStrea

我试图通过URL连接获取整个网页

最有效的方法是什么

我已经在这样做了:

URL url = new URL("http://www.google.com/");
URLConnection connection;
connection = url.openConnection();
InputStream in = connection.getInputStream();        
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
StringBuffer html = new StringBuffer();
String line = bf.readLine();
while(line!=null){
    html.append(line);
    line = bf.readLine();
}
bf.close();
html包含整个html页面。

我认为这是最好的方法。页面的大小是固定的(“它就是它本身”),因此您无法提高内存。也许你可以压缩内容,一旦你有他们,但他们不是非常有用的形式。我可以想象,最终您会希望将HTML解析为DOM树

你所做的任何并行阅读都会使解决方案过于复杂

我建议使用默认大小为2048或4096的StringBuilder

为什么你认为你发布的代码是不够的?你听起来好像犯了过早优化的错误


使用现有资源运行,晚上睡觉。

您可以尝试使用apache中的commons io(http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html)


您的方法看起来相当不错,但是可以通过避免为每行创建中间字符串对象来提高效率

方法是直接读入临时char[]缓冲区

下面是一个稍加修改的代码版本,用于执行此操作(为了清晰起见,减去所有错误检查、异常处理等):


为了获得更好的性能,如果要频繁调用此代码,您当然可以做一些额外的事情,例如预分配字符数组和StringBuffer。

您希望如何处理获得的HTML?解析它?知道一个稍微像样的HTML解析器可能已经有了一个构造函数或方法参数,它直接接受
URL
InputStream
,这样您就不必担心流式处理的性能了

假设您想做的事情如中所述,例如,您可以非常轻松地获得所有这些新闻链接,如下所示:

Document document = Jsoup.connect("http://news.google.com.ar/nwshp?hl=es&tab=wn").get();
Elements newsLinks = document.select("h2.title a:eq(0)");
for (Element newsLink : newsLinks) {
    System.out.println(newsLink.attr("href"));
}
仅几秒钟后就会产生以下结果:

http://www.infobae.com/mundo/541259-100970-0-Pinera-confirmo-que-el-rescate-comenzara-las-20-y-durara-24-y-48-horas http://www.lagaceta.com.ar/nota/403112/Argentina/Boudou-disculpo-con-DAIA-pero-volvio-cuestionar-medios.html http://www.abc.es/agencias/noticia.asp?noticia=550415 http://www.google.com/hostednews/epa/article/ALeqM5i6x9rhP150KfqGJvwh56O-thi4VA?docId=1383133 http://www.abc.es/agencias/noticia.asp?noticia=550292 http://www.univision.com/contentroot/wirefeeds/noticias/8307387.shtml http://noticias.terra.com.ar/internacionales/ecuador-apoya-reclamo-argentino-por-ejercicios-en-malvinas,3361af2a712ab210VgnVCM4000009bf154d0RCRD.html http://www.infocielo.com/IC/Home/index.php?ver_nota=22642 http://www.larazon.com.ar/economia/Cristina-Fernandez-Censo-indispensable-pais_0_176100098.html http://www.infobae.com/finanzas/541254-101275-0-Energeticas-llevaron-la-Bolsa-portena-ganancias http://www.telam.com.ar/vernota.php?tipo=N&idPub=200661&id=381154&dis=1&sec=1 http://www.ambito.com/noticia.asp?id=547722 http://www.canal-ar.com.ar/noticias/noticiamuestra.asp?Id=9469 http://www.pagina12.com.ar/diario/cdigital/31-154760-2010-10-12.html http://www.lanacion.com.ar/nota.asp?nota_id=1314014 http://www.rpp.com.pe/2010-10-12-ganador-del-pulitzer-destaca-nobel-de-mvll-noticia_302221.html http://www.lanueva.com/hoy/nota/b44a7553a7/1/79481.html http://www.larazon.com.ar/show/sdf_0_176100096.html http://www.losandes.com.ar/notas/2010/10/12/batista-siento-comodo-dieron-respaldo-520595.asp http://deportes.terra.com.ar/futbol/los-rumores-empiezan-a-complicar-la-vida-de-river-y-vuelve-a-sonar-gallego,a24483b8702ab210VgnVCM20000099f154d0RCRD.html http://www.clarin.com/deportes/futbol/Exigieron-Roman-regreso-Huracan_0_352164993.html http://www.el-litoral.com.ar/leer_noticia.asp?idnoticia=146622 http://www.nuevodiarioweb.com.ar/nota/181453/Locales/C%C3%A1ncer_mama:_200_casos_a%C3%B1o_Santiago.html http://www.ultimahora.com/notas/367322-Funcionarios-sanitarios-capacitaran-sobre-cancer-de-mama http://www.lanueva.com/hoy/nota/65092f2044/1/79477.html http://www.infobae.com/policiales/541220-101275-0-Se-suspendio-la-declaracion-del-marido-Fernanda-Lemos http://www.clarin.com/sociedad/educacion/titulo_0_352164863.html http://www.infobae.com/mundo/541259-100970-0-Pinera-confirmo-que-el-rescate-comenzara-las-20-y-durara-24-y-48-horas http://www.lagaceta.com.ar/nota/403112/Argentina/Boudou-disculpo-con-DAIA-pero-volvio-cuestionar-medios.html http://www.abc.es/agencias/noticia.asp?noticia=550415 http://www.google.com/hostednews/epa/article/ALeqM5i6x9rhP150KfqGJvwh56O-thi4VA?docId=1383133 http://www.abc.es/agencias/noticia.asp?noticia=550292 http://www.univision.com/contentroot/wirefeeds/noticias/8307387.shtml http://noticias.terra.com.ar/internacionales/ecuador-apoya-reclamo-argentino-por-ejercicios-en-malvinas,3361AF2A712AB210VGNVCM400009BF154D0RCRD.html http://www.infocielo.com/IC/Home/index.php?ver_nota=22642 http://www.larazon.com.ar/economia/Cristina-Fernandez-Censo-indispensable-pais_0_176100098.html http://www.infobae.com/finanzas/541254-101275-0-Energeticas-llevaron-la-Bolsa-portena-ganancias http://www.telam.com.ar/vernota.php?tipo=N&idPub=200661&id=381154&dis=1&sec=1 http://www.ambito.com/noticia.asp?id=547722 http://www.canal-ar.com.ar/noticias/noticiamuestra.asp?Id=9469 http://www.pagina12.com.ar/diario/cdigital/31-154760-2010-10-12.html http://www.lanacion.com.ar/nota.asp?nota_id=1314014 http://www.rpp.com.pe/2010-10-12-ganador-del-pulitzer-destaca-nobel-de-mvll-noticia_302221.html http://www.lanueva.com/hoy/nota/b44a7553a7/1/79481.html http://www.larazon.com.ar/show/sdf_0_176100096.html http://www.losandes.com.ar/notas/2010/10/12/batista-siento-comodo-dieron-respaldo-520595.asp http://deportes.terra.com.ar/futbol/los-rumores-empiezan-a-complicar-la-vida-de-river-y-vuelve-a-sonar-gallego,a24483b8702ab210VgnVCM20000099f154d0RCRD.html http://www.clarin.com/deportes/futbol/Exigieron-Roman-regreso-Huracan_0_352164993.html http://www.el-litoral.com.ar/leer_noticia.asp?idnoticia=146622 http://www.nuevodiarioweb.com.ar/nota/181453/Locales/C%C3%A1ncer_mama:_200_casos_a%C3%B1o_Santiago.html http://www.ultimahora.com/notas/367322-Funcionarios-sanitarios-capacitaran-sobre-cancer-de-mama http://www.lanueva.com/hoy/nota/65092f2044/1/79477.html http://www.infobae.com/policiales/541220-101275-0-Se-suspendio-la-declaracion-del-marido-Fernanda-Lemos http://www.clarin.com/sociedad/educacion/titulo_0_352164863.html 有人说过regex绝对是解析HTML的错误工具吗?;)

另见:

    • 有一些技术上的考虑。您可能希望使用HTTPURLConnection而不是URLConnection

      HTTPURLConnection支持分块传输编码,这允许您以分块方式处理数据,而不是在开始工作之前缓冲所有内容。这可以改善用户体验

      此外,HTTPURLConnection支持持久连接。如果要立即请求其他资源,为什么要关闭该连接?保持与web服务器的TCP连接处于打开状态允许应用程序快速下载多个资源,而无需花费为每个资源建立新TCP连接的开销(延迟)


      告诉服务器您支持gzip,如果响应头表示内容已压缩,则在GZIPInputStream周围包装一个BufferedReader。

      定义“高效”的含义。嗯,这是最好的方法。花费更少的时间和资源。我不是IO方面的专家,因此我很难评估替代方案。我认为这是最好的方法,使用StringBuffer非常好,而且帮助很大,因为它创建的对象更少,我不会做任何不同的事情。您当前的瓶颈是什么?你想用CPU周期换取带宽吗?此方法不支持gzip。如果我没记错的话,
      readLine()
      会剥离脱机分隔符,因此如果您没有显式地将它们放回原处,您的输出会将它们全部剥离。此外,如果这是java 1.5或更新的,考虑使用<代码> StringBuilder <代码>
      Document document = Jsoup.connect("http://news.google.com.ar/nwshp?hl=es&tab=wn").get();
      Elements newsLinks = document.select("h2.title a:eq(0)");
      for (Element newsLink : newsLinks) {
          System.out.println(newsLink.attr("href"));
      }
      
      http://www.infobae.com/mundo/541259-100970-0-Pinera-confirmo-que-el-rescate-comenzara-las-20-y-durara-24-y-48-horas http://www.lagaceta.com.ar/nota/403112/Argentina/Boudou-disculpo-con-DAIA-pero-volvio-cuestionar-medios.html http://www.abc.es/agencias/noticia.asp?noticia=550415 http://www.google.com/hostednews/epa/article/ALeqM5i6x9rhP150KfqGJvwh56O-thi4VA?docId=1383133 http://www.abc.es/agencias/noticia.asp?noticia=550292 http://www.univision.com/contentroot/wirefeeds/noticias/8307387.shtml http://noticias.terra.com.ar/internacionales/ecuador-apoya-reclamo-argentino-por-ejercicios-en-malvinas,3361af2a712ab210VgnVCM4000009bf154d0RCRD.html http://www.infocielo.com/IC/Home/index.php?ver_nota=22642 http://www.larazon.com.ar/economia/Cristina-Fernandez-Censo-indispensable-pais_0_176100098.html http://www.infobae.com/finanzas/541254-101275-0-Energeticas-llevaron-la-Bolsa-portena-ganancias http://www.telam.com.ar/vernota.php?tipo=N&idPub=200661&id=381154&dis=1&sec=1 http://www.ambito.com/noticia.asp?id=547722 http://www.canal-ar.com.ar/noticias/noticiamuestra.asp?Id=9469 http://www.pagina12.com.ar/diario/cdigital/31-154760-2010-10-12.html http://www.lanacion.com.ar/nota.asp?nota_id=1314014 http://www.rpp.com.pe/2010-10-12-ganador-del-pulitzer-destaca-nobel-de-mvll-noticia_302221.html http://www.lanueva.com/hoy/nota/b44a7553a7/1/79481.html http://www.larazon.com.ar/show/sdf_0_176100096.html http://www.losandes.com.ar/notas/2010/10/12/batista-siento-comodo-dieron-respaldo-520595.asp http://deportes.terra.com.ar/futbol/los-rumores-empiezan-a-complicar-la-vida-de-river-y-vuelve-a-sonar-gallego,a24483b8702ab210VgnVCM20000099f154d0RCRD.html http://www.clarin.com/deportes/futbol/Exigieron-Roman-regreso-Huracan_0_352164993.html http://www.el-litoral.com.ar/leer_noticia.asp?idnoticia=146622 http://www.nuevodiarioweb.com.ar/nota/181453/Locales/C%C3%A1ncer_mama:_200_casos_a%C3%B1o_Santiago.html http://www.ultimahora.com/notas/367322-Funcionarios-sanitarios-capacitaran-sobre-cancer-de-mama http://www.lanueva.com/hoy/nota/65092f2044/1/79477.html http://www.infobae.com/policiales/541220-101275-0-Se-suspendio-la-declaracion-del-marido-Fernanda-Lemos http://www.clarin.com/sociedad/educacion/titulo_0_352164863.html