Read all standard input into a Java byte array

后端 未结 2 676
慢半拍i
慢半拍i 2021-01-23 22:44

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 prov

2条回答
  •  温柔的废话
    2021-01-23 23:19

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

提交回复
热议问题