user3579421
user3579421

Reputation: 45

How do you read from an InputStream in Java and convert to byte array?

I am currently trying to read in data from a server response. I am using a Socket to connect to a server, creating a http GET request, then am using a Buffered Reader to read in data. Here is what the code looks like compacted:

    Socket conn = new Socket(server, 80);
    //Request made here
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String response;
    while((response = inFromServer.readLine()) != null){
        System.out.println(response);
    }

I would like to read in the data, instead of as a String, as a byte array, and write it to a file. How is this possible? Any help is greatly appreciated, thank you.

Upvotes: 2

Views: 7905

Answers (4)

AdityaKeyal
AdityaKeyal

Reputation: 1228

You need to use a ByteArrayOutputStream, do something like the below code:

Socket conn = new Socket(server, 80);
        //Request made here
        InputStream is = conn.getInputStream();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int readBytes = -1;

        while((readBytes = is.read(buffer)) > 1){
            baos.write(buffer,0,readBytes);
        }

        byte[] responseArray = baos.toByteArray();

Upvotes: 4

Niraj Patel
Niraj Patel

Reputation: 2208

If you are not using Apache commons-io library in your project,I have pretty simple method to do the same without using it..

   /*
     * Read bytes from inputStream and writes to OutputStream,
     * later converts OutputStream to byte array in Java.
     */
    public static byte[] toByteArrayUsingJava(InputStream is)
    throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int reads = is.read();

        while(reads != -1){
            baos.write(reads);
            reads = is.read();
        }

        return baos.toByteArray();

    }

Upvotes: 1

morgano
morgano

Reputation: 17422

With plain java:

    ByteArrayOutputStream output = new ByteArrayOutputStream();

    try(InputStream stream = new FileInputStream("myFile")) {
        byte[] buffer = new byte[2048];
        int numRead;
        while((numRead = stream.read(buffer)) != -1) {
            output.write(buffer, 0, numRead);
        }
    } catch(IOException e) {
        e.printStackTrace();
    }

    // and here your bytes
    byte[] myDesiredBytes = output.toByteArray();

Upvotes: 1

Suren Raju
Suren Raju

Reputation: 3060

One way is to use Apache commons-io IOUtils

byte[] bytes = IOUtils.toByteArray(inputstream);

Upvotes: 1

Related Questions