/**
* 读图片
* @return
* @throws Exception
*/
public static void getLocalPicture(){
//本地存放图图片路径及图片名
File localFile = new File("D:\\city\\HaierVR.jpg");
try {
//网络图片
URL url = new URL("https://123p1.sogoucdn.com/imgu/2018/09/20180929144630_391.jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
saveFile(is, localFile );
System.out.println("读取成功");
} catch (MalformedURLException e) {
System.out.println("读取失败");
e.printStackTrace();
} catch (IOException e) {
System.out.println("读取失败");
e.printStackTrace();
}
}
/**
*下载图片到本地
* @param is
* @param dstFile
*/
public static void saveFile(InputStream is,File localFile ){
FileOutputStream fos = null;
File parentFile = localFile .getParentFile();
if(!parentFile.exists()){
parentFile.mkdirs();
}
try {
fos = new FileOutputStream(localFile );
byte[] buff = new byte[1024 * 4];
int len;
while((len = is.read(buff)) != -1){
fos.write(buff, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
if(is != null){
is.close();
}
if(fos != null){
fos.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}