public static void downLoadImg(String imgName, String imgUrl, String fileURL) throws Exception{
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
// 创建流
System.out.println("imgUrl:" + imgUrl);
in = new BufferedInputStream( new URL(imgUrl).openStream());
// 生成图片名
int index = imgUrl.lastIndexOf("/");
String sName = imgName == null ? imgUrl.substring(index + 1, imgUrl.length()) : imgName;
File fir = new File(fileURL);
if (!fir.exists()) {
fir.mkdirs();
}
// 存放地址
File img = new File(fileURL + sName);
// 生成图片
out = new BufferedOutputStream( new FileOutputStream(img));
byte[] buf = new byte[2048];
int length = in.read(buf);
while (length != -1) {
out.write(buf, 0, length);
length = in.read(buf);//在一个下载图片的线程有的时候读取到这里就不动了 ,这种问题应该怎么解决
}
} catch (Exception e) {
System.out.println("下载图片异常");
e.printStackTrace();
throw new RuntimeException("下载图片异常");
} finally{
try {
if( in != null){
in.close();
}
if(out != null){
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
打印一些信息调试一个那个地方,看有没有死循环。
多大的图片呀?理论上不会这样吧
没设超时时间吧,内容不够十个字
简单测试了一下么有问题啊。检查下图片路径。
这是线程调试的地方::::
// 存放地址
File img = new File(fileURL + sName);
// 生成图片
out = new BufferedOutputStream( new FileOutputStream(img));
byte[] buf = new byte[2048];
int length = in.read(buf);
System.out.println(111111111);
while (length != -1) {
System.out.println(222222);
out.write(buf, 0, length);
System.out.println(3333333);
length = in.read(buf);//在一个下载图片的线程有的时候读取到这里就不动了 ,这种问题应该怎么解决
System.out.println(4444444);
}
System.out.println(55555555);
打印日志:
111111111
222222
3333333
4444444
222222
3333333
4444444
222222
3333333
4444444
222222
3333333
4444444
222222
3333333
4444444
222222
3333333
4444444
222222
3333333
4444444
222222
3333333
4444444
222222
3333333
4444444
222222
3333333
4444444
222222
3333333
4444444
222222
3333333
4444444
222222
3333333
4444444
222222
3333333 最后停的地方。。