Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - download a file through network with a buffer

i want to read from a network stream and write the bytes to a file, directly. But every time i run the program very few bytes are written to the file actually.

Java:

InputStream in = uc.getInputStream();
int clength=uc.getContentLength();
byte[] barr = new byte[clength];
int offset=0;
int totalwritten=0;
int i;
int wrote=0;

OutputStream out = new FileOutputStream("file.xlsx");
while(in.available()!=0) { 
   wrote=in.read(barr, offset, clength-offset);
   out.write(barr, offset, wrote);
   offset+=wrote;
   totalwritten+=wrote;
}
System.out.println("Written: "+totalwritten+" of "+clength);
out.flush();
like image 796
Giorgos Fandomas Avatar asked Dec 14 '25 09:12

Giorgos Fandomas


1 Answers

That's because available() doesn't do what you think it does. Read its API documentation. You should simply read until the number of bytes read, returned by read(), is -1. Or even simpler, use Files.copy():

Files.copy(in, new File("file.xlsx").toPath());

Using a buffer that has the size of the input stream also pretty much defeats the purpose of using a buffer, which is to only have a few bytes in memory.

If you want to reimplement copy(), the general pattern is the following:

byte[] buffer = new byte[4096]; // number of bytes in memory
int numberOfBytesRead;
while ((numberOfBytesRead = in.read(buffer)) >= 0) {
    out.write(buffer, 0, numberOfBytesRead);
}
like image 165
JB Nizet Avatar answered Dec 15 '25 23:12

JB Nizet