0

I am trying to get the byte array data in the InputStream by calling the getBytes() method but nothing is being printed in the console. The count hat the vlaue 9. How can I print out the bytes of the InputStream?

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class Test {

    public static void main(String args[]) throws Exception {
        InputStream inputStream = null;
        ServerSocket serverSocket = new ServerSocket(27015);
        while (true) {
            Socket clientSocket = serverSocket.accept();
            inputStream = clientSocket.getInputStream();
            byte[] temp = new byte[512];
            int count = inputStream.read(temp); // here I am getting 9
            byte[] byteData = Test.getBytes(inputStream); // byteData is here empty.
            System.out.println("byteData: " + byteData);

        }
    }


    public static byte[] getBytes(InputStream is) throws IOException {

        int len;
        int size = 512;
        byte[] buf;

        if (is instanceof ByteArrayInputStream) {
            size = is.available();
            buf = new byte[size];
            len = is.read(buf, 0, size);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            buf = new byte[size];
            while ((len = is.read(buf, 0, size)) != -1) {
                bos.write(buf, 0, len);
            }
            buf = bos.toByteArray();
        }
        return buf;
    }

}

1 Answer 1

2

in the line:

  int count = inputStream.read(temp); // here I am getting 9

you have read the file alredy until the end,

so the line:

        byte[] byteData = Test.getBytes(inputStream); // byteData is here empty.

has nothing to read.

So you should remove the first line and take the length of the Array as number of Bytes in your Input stream

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.