如何使用相同的 InputStreamReader 轮询 URL

How to poll a URL using the same InputStreamReader

我有一个 URL,它会不断更新我想要检索的新数据。我编写这段代码是为了每 5 秒检索一次内容,但是 reader 在一次迭代后为 null。

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 实例?

您需要重新创建输入流(即 'is')。所以你需要一次又一次地重新打开连接。并关闭它,如果你喜欢它 while(true).

我不相信 reader 是空的,可能刚刚达到 EOS。

这是 InputStreamReader 扩展的 Reader class 的文档:

/** * 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() 方法,因此您将无法使用它来重置流。您将需要找到一个不同的实现来完成您正在寻找的东西。或者您可以在每次迭代时重新创建流。根据性能问题,只要您在每次迭代结束时关闭打开的资源,这可能不是问题。

希望对您有所帮助。