将所有标准输入读入Java字节数组

时间:2013-09-21 18:38:26

标签: java unix stdin

现代Java中最简单的方法(仅使用标准库)将所有标准输入读取到EOF到字节数组中,最好不必自己提供该数组? stdin数据是二进制数据,不是来自文件。

即。类似于Ruby的

foo = $stdin.read

我能想到的唯一部分解决方案是

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来说,这看起来也很奇怪,并使用固定大小的缓冲区。

2 个答案:

答案 0 :(得分:2)

我使用Guava及其ByteStreams.toByteArray方法:

byte[] data = ByteStreams.toByteArray(System.in);

不使用任何第三方库,我会使用ByteArrayOutputStream和临时缓冲区:

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的方法中封装,然后基本上等同于ByteStreams.toByteArray ......

答案 1 :(得分:1)

如果您正在阅读文件,Files.readAllBytes就是这样做的。

否则,我会使用ByteBuffer:

ByteBuffer buf = ByteBuffer.allocate(1000000);
ReadableByteChannel channel = Channels.newChannel(System.in);
while (channel.read(buf) >= 0)
    ;
buf.flip();
byte[] bytes = Arrays.copyOf(buf.array(), buf.limit());