'How to Check and Read Number of bytes present in a socket into a byte array in java?

I have a C# server that is sending a file (in bytes) to my JAVA client. Currently I am using DataInputStream to read data from socket with a buffer size of 1024 bytes and then storing that data in a file.

  1. Can anyone tell me how I would know how much data I have received in my socket so that I would adjust my bufferSize accordingly?

  2. Is there any other way except DataInputStream to read incoming byte data in data from a socket?

Code:

DataInputStream In = new DataInputStream(socket.getInputStream());

FileOutputStream fos = new FileOutputStream(getFilePath(fileName));

int bytesRead = 0;
int bufferSize = 1024;

byte[] data = new byte[bufferSize];

// fileSize is the int Variable having total Bytes of file that is being sent by server
while (bytesRead < fileSize)
{
    bytesRead += dIn.read(data, 0, bufferSize);
    fos.write(data);
}

Hint: I know the size of the incoming file.



Solution 1:[1]

After a long search, I found one solution. Not perfectly fine, but somehow, it did the job. I used dataInputStream.available() to check how many bytes are available and then only read that number of available bytes.

Code:

DataInputStream dIn = new DataInputStream(socket.getInputStream());

FileOutputStream fos = new FileOutputStream(getFilePath(fileName));

int availableBytes = dIn.available();

while (availableBytes> 0) {

Log.d(TAG, "data is available");
size = dIn.read(data, 0, availableBytes);
fos.write(data, 0, size);
availableBytes = dIn.available();

}
            
            

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aqib Naveed