我在服务器上有40 MB的文件,我正在下载我的文件使用
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);这段代码看起来运行得很好,但时间太长了。有没有什么方法可以让这个过程更快。
/minhaz
发布于 2010-07-22 05:03:44
使用大于1 KB的输入缓冲区。清空缓冲区的速度越快,网络堆栈可以继续下载的速度就越快。这应该会有帮助:
byte[] buffer = new byte[50*1024];发布于 2010-07-22 12:00:57
我也有同样的问题,想出了这个代码。比我以前尝试过的版本更快。我指定的缓冲区大小大于要下载的文件的大小。希望能有所帮助。
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;
}https://stackoverflow.com/questions/3302993
复制相似问题