java图片路径url_java下载网页URL图片到项目路径下

我不是女神ヾ 2022-11-08 14:07 270阅读 0赞

/**

* 下载网页URL的图片到项目中

* @param urlPath 图片地址

* @return Moses

* @throws IOException

*/

public static String downLoadFile(String urlPath) throws IOException {

// 构造URL

URL url = new URL(urlPath);

// 打开连接

URLConnection con = url.openConnection();

//设置请求超时为5s

con.setConnectTimeout(5*1000);

// 输入流

InputStream is = con.getInputStream();

// 1K的数据缓冲

byte[] bs = new byte[1024];

// 读取到的数据长度

int len;

String name = (String.valueOf(Math.random()*100000)).substring(0,5);

// 输出的文件流

String path = ClassUtils.getDefaultClassLoader().getResource(“”).getPath() +”/image/“+name+”.jpg”;

File sf=new File(path);

File dir=new File(sf.getPath().replace(sf.getName(),””));

if(!dir.exists()) {

dir.mkdirs();

}

OutputStream os = new FileOutputStream(sf);

// 开始读取

while ((len = is.read(bs)) != -1) {

os.write(bs, 0, len);

}

// 完毕,关闭所有链接

os.close();

is.close();

return path;

}

发表评论

表情:
评论列表 (有 0 条评论,270人围观)

还没有评论,来说两句吧...

相关阅读