文章目录
提示:以下是本篇文章正文内容,下面案例可供参考
测试类
/**
* 保存url文件到本地
* @param urlString 文件url
* @param filePath 本地写入文件路径
* @return filePath 保存文件地址
* @throws Exception
*/
public static String downloadImg(String urlString,String filePath) throws Exception {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
File file = new File(filePath);
FileOutputStream os = new FileOutputStream(file, true);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
return filePath;
}