Pregunta

La aplicación que estoy trabajando tiene una carga de la página web terriblemente lento. Si funciono el siguiente código funciona bien, pero sólo a causa de la llamada a sleep. Si no duermo entonces el InputStream es sólo un montón de espacios, probablemente debido a la aplicación que está llamando. ¿Hay alguna manera de no cortar alrededor de esto?

public class PublishTool extends Thread {

  private URL publishUrl;

  private String filerLocation;

  public PublishTool() {
  }

  public PublishTool(String publishUrl, String filerLocation) throws NibException {

    try {
      this.publishUrl = new URL(publishUrl);
    } catch (MalformedURLException e) {
      throw new NibException("Publish Url :" + publishUrl + " is not valid. ");
    }

    this.filerLocation = filerLocation;

  }

  public void run() {

    File filerFile = new File(filerLocation);
    BufferedWriter writer = null;


    try {
      URLConnection conn = publishUrl.openConnection();
      BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream())));

      writer = new BufferedWriter(new FileWriter(filerLocation));

      Thread.sleep(1000l);

      while (reader.ready()) {
        writer.write(reader.readLine() + "\n");
      }

    } catch (MalformedURLException e) {
      throw new IllegalStateException("Malformed URL for : " + publishUrl + " " + filerLocation, e);
    } catch (IOException e) {
      throw new IllegalStateException("IO Exception for  : " + publishUrl + " " + filerLocation, e);
    } catch (InterruptedException e) {
      throw new IllegalStateException("Thread was interrupted early... publishing might have failed.");
    } catch (NibException e) {
      throw new IllegalStateException("Publishing File Copy failed : " + filerLocation + ".bak" + " to " + filerLocation);
    } finally {
      try {
        writer.flush();
        writer.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
¿Fue útil?

Solución

No utilice reader.ready (). Sólo tiene que llamar readLine () y dejar readLine bloque () hasta que esté listo de los datos. El final de los datos generalmente se señaliza con una línea nula.

En el caso de un amable, un par de ejemplos de código en mi sitio web: lectura de una URL.

Otros consejos

En primer lugar, sería útil si usted envió su código real.

Mi conjetura el problema está llamando Reader.ready. Al igual que en InputStream.available, que devuelve true si ya está tamponada de entrada. Si tiene que esperar a que, por ejemplo, una toma de la que volverá false. Generalmente no es necesario ready. Utilice readLine, y salir del bucle si devuelve null (para el extremo de la corriente).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top