问题描述
现代Java中最简单的方法(仅使用标准库)将所有标准输入读取到EOF到字节数组中,最好不必自己提供该数组? stdin数据是二进制数据,不是来自文件。
What's the simplest way in modern Java (using only the standard libraries) to read all of standard input until EOF into a byte array, preferably without having to provide that array oneself? The stdin data is binary stuff and doesn't come from a file.
I.e。 Ruby之类的东西
I.e. something like Ruby's
foo = $stdin.read
我能想到的唯一部分解决方案是
The only partial solution I could think of was along the lines of
byte[] buf = new byte[1000000];
int b;
int i = 0;
while (true) {
b = System.in.read();
if (b == -1)
break;
buf[i++] = (byte) b;
}
byte[] foo[i] = Arrays.copyOfRange(buf, 0, i);
...但即使对Java来说,这看起来也很奇怪,并使用固定大小的缓冲区。
... but that seems bizarrely verbose even for Java, and uses a fixed size buffer.
推荐答案
我使用及其方法:
I'd use Guava and its ByteStreams.toByteArray
method:
byte[] data = ByteStreams.toByteArray(System.in);
如果不使用任何第三方库,我会使用 ByteArrayOutputStream
和一个临时缓冲区:
Without using any 3rd party libraries, I'd use a ByteArrayOutputStream
and a temporary buffer:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[32 * 1024];
int bytesRead;
while ((bytesRead = System.in.read(buffer)) > 0) {
baos.write(buffer, 0, bytesRead);
}
byte[] bytes = baos.toByteArray();
...可能在接受 InputStream $的方法中封装它c $ c>,这基本上等于
ByteStreams.toByteArray
无论如何......
... possibly encapsulating that in a method accepting an InputStream
, which would then be basically equivalent to ByteStreams.toByteArray
anyway...
这篇关于将所有标准输入读入Java字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!