gpt4 book ai didi

java - 从 Stream 中读取一行并立即返回

转载 作者:行者123 更新时间:2023-12-01 15:10:31 24 4
gpt4 key购买 nike

我应该使用哪种方法(以及哪个类)从给定的输入流中读取一行,如果没有行可以读取,或者实际上在任何情况下都立即返回?

为了清楚起见,我想知道哪个类提供了一种从 InputStream 读取行并立即返回的方法 - 例如,如果没有要读取的行,则不阻塞。

例如,据我所知,BufferedReader.readLine() 确实会阻塞。

最佳答案

public final String pollLine(final BufferedReader reader)
throws IOException {
/* pick a reasonable look ahead */
reader.mark(512);
while (reader.ready()) {
final int ch = reader.read();
if (ch == -1
|| Character.getType(ch) == Character.LINE_SEPARATOR) {
reader.reset();
return reader.readLine();
}
}
reader.reset();
return null;
}

对于任何错误,我们深表歉意,我是在手机的小触摸屏键盘上输入此回复的。

要回答您的问题,您可以查询Reader.ready以确定您是否可以安全地读取而不会阻塞。

Returns:

True if the next read() is guaranteed not to block for input, false otherwise. Note that returning false does not guarantee that the next read will block.

关于java - 从 Stream 中读取一行并立即返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12413573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com