Convert InputStream to byte array in Java

前端 未结 30 3533
無奈伤痛
無奈伤痛 2020-11-21 12:08

How do I read an entire InputStream into a byte array?

30条回答
  •  终归单人心
    2020-11-21 12:54

    In-case someone is still looking for a solution without dependency and If you have a file.

    DataInputStream

     byte[] data = new byte[(int) file.length()];
     DataInputStream dis = new DataInputStream(new FileInputStream(file));
     dis.readFully(data);
     dis.close();
    

    ByteArrayOutputStream

     InputStream is = new FileInputStream(file);
     ByteArrayOutputStream buffer = new ByteArrayOutputStream();
     int nRead;
     byte[] data = new byte[(int) file.length()];
     while ((nRead = is.read(data, 0, data.length)) != -1) {
         buffer.write(data, 0, nRead);
     }
    

    RandomAccessFile

     RandomAccessFile raf = new RandomAccessFile(file, "r");
     byte[] data = new byte[(int) raf.length()];
     raf.readFully(data);
    

提交回复
热议问题