I have 40 MB file in server and i am downloading my file using
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File("trips.xml"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) != -1 ) {
f.write(buffer,0, len1);
开发者_如何学Go
this code seems working fine but it is taking too long. is their any way I can make this process faster.
/minhaz
Use larger input buffer than 1 KB. The faster you empty buffer, the faster network stack can continue downloading. This should help:
byte[] buffer = new byte[50*1024];
This very ugly hack which might give you a faster download time, or maybe it doesn't, you'll have to test it under your conditions:
Start several parallel connections (in separate threads?), and each one should download a different chunk of data (using HTTP 1.1 Range header). Depending on many things like if there's a full moon, or the sun is out or the roses are blooming you might get better results because it will saturate your link better than a single connection (to the expense of everyone else sharing your link, kinda like what BitTorrent does).
I am having the same problem, came up with this code. Was faster than previous versions I have tried. I specify a buffer size greater than the file I am going to down load. Hope it helps.
public String load(String url, int bufferSize){
try {
URL myURL = new URL(url);
URLConnection ucon = myURL.openConnection();
ucon.setRequestProperty("Connection", "keep-alive");
InputStream inputStream = ucon.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(bufferSize);
byte[] buf = new byte[bufferSize];
int read;
do {
read = bufferedInputStream.read(buf, 0, buf.length);
if (read > 0)
byteArrayBuffer.append(buf, 0, read);
} while (read >= 0);
return new String(byteArrayBuffer.toByteArray());
} catch (Exception e) {
Log.i("Error", e.toString());
}
return null;
}
精彩评论