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

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

即像露比的

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来说似乎也很冗长,并且使用固定大小的缓冲区.

解决方法:

我将使用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 …

上一篇:linux stdbuf – line-buffered stdin选项不存在


下一篇:Nodejs与管道和信号