Read all standard input into a Java byte array

故事扮演 提交于 2019-12-02 13:11:52

问题


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. 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);

... but that seems bizarrely verbose even for Java, and uses a fixed size buffer.


回答1:


I'd use Guava and its ByteStreams.toByteArray method:

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

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();

... possibly encapsulating that in a method accepting an InputStream, which would then be basically equivalent to ByteStreams.toByteArray anyway...




回答2:


If you're reading from a file, Files.readAllBytes is the way to do it.

Otherwise, I'd use a 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());


来源:https://stackoverflow.com/questions/18936195/read-all-standard-input-into-a-java-byte-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!