使用 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 foravailable()
还指出:
The available method for class InputStream always returns 0.
This method should be overridden by subclasses.
实际上,具体的输入流类确实会覆盖 available(),提供有意义的值,而不是常量 0。
第二个警告:确保在 Windows 中输入时使用回车。
如果使用System.in
,您的程序仅在您的命令外壳移交时接收输入。如果您使用文件重定向/管道(例如 somefile > java myJavaApp 或 somecommand | java myJavaApp ),则输入数据通常会立即移交。但是,如果您手动键入输入,则可能会延迟数据交接。例如,使用 windows cmd.exe shell,数据在 cmd.exe shell 中缓冲。数据仅在回车(control-m 或<enter>
)之后传递给正在执行的 java 程序。这是执行环境的限制。当然,只要 shell 缓冲数据, InputStream.available() 就会返回 0 - 这是正确的行为;那时没有可用的数据。一旦数据从 shell 中可用,该方法就会返回一个 > 0 的值。注意:Cygwin 使用 cmd。
最简单的解决方案(没有阻塞,所以不需要超时)
只需使用这个:
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.