[英]How to poll a URL using the same InputStreamReader
我有一個 URL,它不斷更新我想要檢索的新數據。 我寫了這段代碼,每 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
的新實例?
您需要重新創建輸入流(即“是”)。 因此,您需要一次又一次地重新打開連接。 並關閉它,如果你喜歡它(真)。
我不相信讀者是空的,可能剛剛到達 EOS。
以下是 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() 方法,因此您將無法使用它來重置流。 您將需要找到不同的實現來完成您正在尋找的內容。 或者您可以在每次迭代時重新創建流。 根據性能問題,只要您在每次迭代結束時關閉打開的資源,這可能就不是問題。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.