If you know the length, using readFully () is much more efficient than reading a byte at a time.
In this case, you do not need to know the length, you can write a cycle to read / write as much data as possible.
InputStream is = connectionSocket.getInputStream(); byte[] bytes = new byte[8192]; int len; while((len = is.read(bytes)) > 0) fos.write(bytes, 0, len);
You can not read the entire file in memory by copying data while reading.
FileInputStream fis = new FileInputStream(filename); OutputStream os = socket.getOutputStream(); byte[] bytes = new byte[8192]; int len; while((len = fis.read(bytes)) > 0) os.write(bytes, 0, len);
You can use Apache IOUtils .copy () to copy from one stream to another if you want.
This approach has the advantage that the file can be of any size (over 2 GB). Array usage is limited to 2 GB (and uses more memory)
source share