使用 inputStream.available()
System.in.available() 返回 0 总是可以接受的。
我发现了相反的情况 - 它总是返回可用字节数的最佳值。 Javadoc 为InputStream.available()
:
Returns an estimate of the number of bytes that can be read (or skipped over)
from this input stream without blocking by the next invocation of a method for
this input stream.
由于时间/陈旧性,估计是不可避免的。由于新数据不断到来,这一数字可能会被一次性低估。然而,它总是“赶上”下一次调用 - 它应该考虑所有到达的数据,除非是在新调用时到达的数据。当有数据不满足上述条件时永久返回 0。
第一个警告:InputStream 的具体子类负责 available()
InputStream
是一个抽象类。它没有数据源。它拥有可用数据是没有意义的。因此,javadoc 为available()
还指出:
The available method for class InputStream always returns 0.
This method should be overridden by subclasses.
事实上,具体的输入流类确实会覆盖 available(),提供有意义的值,而不是常量 0。
第二个警告:确保在 Windows 中键入输入时使用回车符。
如果使用System.in
,您的程序仅在命令 shell 移交时接收输入。如果您使用文件重定向/管道(例如 somefile > java myJavaApp 或 somecommand | java myJavaApp ),则输入数据通常会立即移交。但是,如果您手动键入输入,则数据切换可能会延迟。例如。对于 Windows cmd.exe shell,数据在 cmd.exe shell 内缓冲。数据仅在回车(control-m 或<enter>
)。这是执行环境的限制。当然,只要 shell 缓冲数据,InputStream.available() 就会返回 0 - 这是正确的行为;目前没有可用数据。一旦从 shell 获得数据,该方法就会返回一个 > 0 的值。注意:Cygwin 也使用 cmd.exe。
最简单的解决方案(无阻塞,因此不需要超时)
只需使用这个:
byte[] inputData = new byte[1024];
int result = is.read(inputData, 0, is.available());
// result will indicate number of bytes read; -1 for EOF with no data read.
或者等效地,
BufferedReader br = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")),1024);
// ...
// inside some iteration / processing logic:
if (br.ready()) {
int readCount = br.read(inputData, bufferOffset, inputData.length-bufferOffset);
}
更丰富的解决方案(在超时时间内最大程度地填充缓冲区)
声明一下:
public static int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis)
throws IOException {
int bufferOffset = 0;
long maxTimeMillis = System.currentTimeMillis() + timeoutMillis;
while (System.currentTimeMillis() < maxTimeMillis && bufferOffset < b.length) {
int readLength = java.lang.Math.min(is.available(),b.length-bufferOffset);
// can alternatively use bufferedReader, guarded by isReady():
int readResult = is.read(b, bufferOffset, readLength);
if (readResult == -1) break;
bufferOffset += readResult;
}
return bufferOffset;
}
然后使用这个:
byte[] inputData = new byte[1024];
int readCount = readInputStreamWithTimeout(System.in, inputData, 6000); // 6 second timeout
// readCount will indicate number of bytes read; -1 for EOF with no data read.