基本实现步骤:
1.建立http连接,获取对象 connection
2.输入流读文件
3.新建存储路径
4.输出流写入数据,并关闭流
public class test {
public static void main(String[] args) {getInternetRes("D:\\demoefile","http://imgsrc.baidu.com/image/c0%3Dshijue1%2C0%2C0%2C294%2C40/sign=3d2175db3cd3d539d530078052ee8325/b7003af33a87e950c1e1a6491a385343fbf2b425.jpg","112.jpg");
}
public static void getInternetRes(String newUrl, String oldUrl, String fileName) {
URL url = null;
HttpURLConnection con = null;
InputStream in = null;
FileOutputStream out = null;
try {
url = new URL(oldUrl);
//建立http连接,得到连接对象
con = (HttpURLConnection) url.openConnection();
//输入流读取文件
in = con.getInputStream();
//转化为byte数组
byte[] data = getByteData(in);
//建立存储的目录、保存的文件名
File file = new File(newUrl+today);
if (!file.exists()) {
file.mkdirs();
}
//修改文件名 用id重命名
File res = new File(file + File.separator + fileName);
//写入输出流
out = new FileOutputStream(res);
out.write(data);
logger.info("下载 successfully!");
} catch (MalformedURLException e) {
logger.error("下载出错!"+e.toString());
} catch (IOException e) {
logger.error("下载出错!"+e.toString());
} finally {
//关闭流
try {
if (null != out)
out.close();
if (null != in)
in.close();
} catch (IOException e) {
logger.error("下载出错!"+e.toString());
}
}
}
return null;
}
/**
*
* @Title: getByteData
* @Description: 从输入流中获取字节数组
* @author zml
* @date Sep 12, 2017 7:38:57 PM
*/
private static byte[] getByteData(InputStream in) throws IOException {
byte[] b = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(b)) != -1) {
bos.write(b, 0, len);
}
if(null!=bos){
bos.close();
}
return bos.toByteArray();
}