以下代码无法下载文件(顺便说一句,clen 是文件的长度):
int pos = 0, total_pos = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while (pos != -1) {
pos = in.read(buffer, 0, BUFFER_SIZE);
total_pos += pos;
out.write(buffer);
setProgress((int) (total_pos * 100 / clen));
}
...但这工作正常:
int buf;
while ((buf = in.read()) != -1)
out.write(buf);
我想知道为什么,即使第二个代码段工作得很快。关于这一点,是否有任何特别的理由使用 byte[] 缓冲区(因为它似乎并不更快,而且 BufferedInputStream 已经使用了自己的缓冲区......?)
最佳答案
这是应该如何完成的。
public static void copyStream(InputStream is, OutputStream os)
{
byte[] buff = new byte[4096];
int count;
try {
while((count = is.read(buff)) > 0)
os.write(buff, 0, count);
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(os != null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
关于java - 使用 BufferedInputStream 下载无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7721167/