Reading binary data from a socket

I am trying to connect to a server and then send it an HTTP request (GET in this case). The idea is to request a file and then get it from the server.

It should work with both text files and binary files (e.g. imgs). I have no problems with text files, it works fine, but I am having problems with binary files.

First I declare a BufferedReader (to read the header and text file) and the DataInput stream:

BufferedReader in_text = new BufferedReader(
    new InputStreamReader(socket.getInputStream()));

DataInputStream in_binary = new DataInputStream(
    new BufferedInputStream(socket.getInputStream()));

Then I read the header using in_text and find out if it is a text file or a binary file. If it is a text file, I read it correctly in StringBuilder. In case this is a binary file, I declare a byte [filesize] and save the following in_binary contents.

byte[] bindata = new byte[filesize];
in_binary.readFully(bindata);

And it does not work. I get an EOFException.

, , , in_binary , . in_binary.

byte[] bindata = new byte[filesize];
in_binary.reset();
in_binary.skip(headersize);
in_binary.readFully(bindata);

.

?

!

PD: , URLConnection . .

+3
2

BufferedReader ( ) - , . , , . , , , , .

, URLConnection, , .

+3

- Reader, . , JVM. , , . .

Apache Commons IO: IOUtils.toByteArray(), [], , , , , , , , .

+1

Source: https://habr.com/ru/post/1773496/


All Articles