Read all standard input into a Java byte array

后端 未结 2 677
慢半拍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:24

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

提交回复
热议问题