这段下载代码为何总是下载的文件不对?
public static int loadFile(File file, String RequestURL) {
int result = 0;
BufferedInputStream inputB = null;
BufferedOutputStream outputB = null;
try {
URL url = new URL(RequestURL);
URLConnection connect = url.openConnection();
InputStream input = connect.getInputStream();
FileOutputStream output = new FileOutputStream(file);
inputB = new BufferedInputStream(input);
outputB = new BufferedOutputStream(output);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = inputB.read(buffer)) != -1) {
outputB.write(buffer);
outputB.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputB.close();
inputB.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
看了下JDK 发现了一点线索
下面是write(byte b) 方法的解释
The write method of FilterOutputStream calls its write method of three arguments with the arguments b, 0, and b.length.
Note that this method does not call the one-argument write method of its underlying stream with the single argument b.
其实这个方法好像是调用write3个参数的方法 放的参数是wtite(byte b, 0, b。length)
而buffer定义的长度是1024
write(buffer, 0, read);使用这个方法时
我将read 和 buffer.length打印对比了下
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
126---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
520---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
948---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
1024---1024
948---1024
207---1024
前面的是read的大小, 发现并不是每次读取数据都是1024个字节 所以写入的长度要用read来定 用buffer.length中间会有空着的地方