有没有大神帮忙看下,问题在哪,不需要提供其他方法,只是想知道这个的问题在哪?
package socket.url;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class CopyOfDownLoad {
public static void main(String[] args) {
// 相关的所有数据流
InputStream is = null;
BufferedInputStream bis =null;
OutputStream os = null;
BufferedOutputStream bos = null;
try {
// 1、想要下载资源的网络地址和要保存的路径
// 资源地址
String string = "http://file28.mafengwo.net/M00/EF/F3/wKgB6lTG9UqAG0o2AA2IG9Yw6Og16.groupinfo.w665_500.jpeg";
// 保存路径
String pathname = "D:/sxtjava/图片.jpg";
URL url = new URL(string);
// 2、通过openStream()获取字节输入流,进行读取;创建一个流用于写入本地文件
// 读取
// is = url.openStream();// 获取字节输入流
//或者
is = url.openConnection().getInputStream();
bis = new BufferedInputStream(is);
byte[] buf = new byte[1024];
// 写入
File file = new File(pathname);
os = new FileOutputStream(file);
bos = new BufferedOutputStream(os);
// 3、读取(下载)、写入(本地保存)
int lenth= bis.read(buf);
// 读取的不为空就继续读取
while (lenth != -1) {
//写入
bos.write(buf,0,buf.length);
bos.flush();//刷新
lenth= bis.read(buf);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4、关闭资源
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bis != null) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
bos.flush();//刷新
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("保存成功!");
}
}
}

写入的时候:bos.write(buf,0,buf.length);这句话错了,应该是 bos.write(buf,0,i);最后一次只能读取有效长度,不能读取整个数组的长度,因为最后一次数组不会完全读完,有空的。
文件没有传输正确或者没有传输完整。
文件结尾不一样啊老铁,打开方式不同