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();
}
}
}
打印一些信息調試一個那個地方,看有沒有死循環。