Reputation: 725
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;
}
}
Upvotes: 0
Views: 275
Reputation: 69495
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
Upvotes: 2