Convert InputStream to byte array in Java

To convert an InputStream to a byte array in Java, you can use the readAllBytes() method of the java.nio.file.Files class from the java.nio.file package.

The readAllBytes() method reads all the bytes from an InputStream and returns them as a byte array. Here is an example of how you can use the readAllBytes() method to convert an InputStream to a byte array in Java:

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class InputStreamToByteArrayExample {
  public static void main(String[] args) throws Exception {
    // Open an InputStream from a file
    InputStream inputStream = Files.newInputStream(Paths.get("file.txt"));

    // Convert the InputStream to a byte array
    byte[] bytes = Files.readAllBytes(inputStream);

    // Close the InputStream
    inputStream.close();
  }
}

This example opens an InputStream from a file using the newInputStream() method of the Files class, and then converts the InputStream to a byte array using the readAllBytes() method. Finally, it closes the InputStream using the close() method.

Note that the readAllBytes() method is available only in Java 11 and later. If you are using an earlier version of Java, you can use the following code to convert an InputStream to a byte array:

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class InputStreamToByteArrayExample {
  public static byte[] toByteArray(InputStream inputStream) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) != -1) {
      outputStream.write(buffer, 0, length);
    }
    return outputStream.toByteArray();
  }
}

This example uses a ByteArrayOutputStream to read the bytes from the InputStream and write them to a byte array. It reads the bytes in chunks of 1024 bytes, and writes them to the output stream until it reaches the end of the InputStream. Finally, it returns the byte array using the toByteArray() method of the ByteArrayOutputStream.

You can use this method as follows:

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class InputStreamToByteArrayExample {
  public static void main(String[] args) throws Exception {
    // Open an InputStream from a file
    InputStream inputStream = Files.newInputStream(Paths.get("file.txt"));

    // Convert the InputStream to a byte array
    byte[] bytes = toByteArray(inputStream);

    // Close the InputStream
    inputStream.close();
  }