如何使用相同的InputStreamReader轮询URL

时间:2015-10-01 19:20:23

标签: java inputstream

我有一个不断更新的网址,我想要检索新数据。我编写此代码每5秒检索一次内容,但是reader在一次迭代后为空。

InputStream is = new URL("someURL").openStream();
Reader reader = new InputStreamReader(is);
Gson gson = new GsonBuilder().create();
while (true){
    Info info = gson.fromJson(reader, Info.class);
    for (Update update : info.updates){
        if (update.type.equals("data")){
            System.out.println(update.toString());
        }
    }
    Thread.sleep(500);
}

是否有可能以某种方式重置reader并使其在下一次迭代中从流中读取更新的数据,或者我是否必须在每次迭代中创建InputStreamReader的新实例?

2 个答案:

答案 0 :(得分:0)

您需要重新创建输入流(即'是')。所以你需要一次又一次地重新打开连接。并关闭它,如果你喜欢这样做(真实)。

我不相信读者是空的,很可能刚刚到达EOS。

答案 1 :(得分:0)

以下是Reader类的文档,InputStreamReader扩展了:

/** * Resets the stream. If the stream has been marked, then attempt to * reposition it at the mark. If the stream has not been marked, then * attempt to reset it in some way appropriate to the particular stream, * for example by repositioning it to its starting point. Not all * character-input streams support the reset() operation, and some support * reset() without supporting mark(). * * @exception IOException If the stream has not been marked, * or if the mark has been invalidated, * or if the stream does not support reset(), * or if some other I/O error occurs */ public void reset() throws IOException { throw new IOException("reset() not supported"); }

InputStreamReader不会覆盖reset()方法,因此您将无法使用它来重置流。您需要找到一个不同的实现来完成您正在寻找的内容。或者您可以在每次迭代时重新创建流。根据性能问题,只要在每次迭代结束时关闭开放资源,这可能不是问题。

希望这有帮助。