0

私が取り組んでいるアプリケーションの Web ページの読み込みが非常に遅いです。次のコードを実行すると正常に動作しますが、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() をブロックさせます。通常、データの終わりはヌル行で通知されます。

役立つ場合は、私の Web サイトにいくつかのコード例を示します: reading from a URL

于 2009-04-16T00:00:35.323 に答える
1

まず、実際のコードを投稿していただけると助かります。

私の推測では、問題はReader.ready. と同様に、既にバッファリングされた入力がある場合にInputStream.available返されます。trueたとえば、ソケットを待つ必要がある場合は、 を返しfalseます。通常は必要ありませんready。を使用readLineし、ループが返された場合はループから抜け出しますnull(ストリームの最後)。

于 2009-04-15T23:40:34.013 に答える