Reading a binary input stream into a single byte array in Java

前端 未结 6 1926
陌清茗
陌清茗 2020-11-27 18:10

The documentation says that one should not use available() method to determine the size of an InputStream. How can I read the whole content of an <

6条回答
  •  误落风尘
    2020-11-27 18:44

    You can use Apache commons-io for this task:

    Refer to this method:

    public static byte[] readFileToByteArray(File file) throws IOException
    

    Update:

    Java 7 way:

    byte[] bytes = Files.readAllBytes(Paths.get(filename));
    

    and if it is a text file and you want to convert it to String (change encoding as needed):

    StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString()
    

提交回复
热议问题