0

我正在处理的应用程序的网页加载速度非常慢。如果我运行以下代码,它可以正常工作,但只是因为调用sleep. 如果我不睡觉,那么 InputStream 只是一堆空格,可能是由于它正在调用的应用程序。有没有解决这个问题的非黑客方法?

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();
      }
    }
  }
4

2 回答 2

4

不要使用 reader.ready()。只需调用 readLine() 并让 readLine() 阻塞,直到数据准备好。数据的结束通常会以空线表示。

如果有帮助,我的网站上有几个代码示例:从 URL 读取

于 2009-04-16T00:00:35.323 回答
1

首先,如果您发布实际代码会很有帮助。

我猜问题出在Reader.ready. 与 类似,如果已经有缓冲输入InputStream.available,则返回。true如果它需要等待,比如说,它会返回一个套接字false。一般不需要ready。使用readLine, 如果它返回则退出循环null(用于流结束)。

于 2009-04-15T23:40:34.013 回答