首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 互联网 >

从互联网络保存图片到本地

2012-12-19 
从互联网保存图片到本地public byte[] saveImage(String filePath) {FileOutputStream fos nullBuffere

从互联网保存图片到本地
public byte[] saveImage(String filePath) {
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpUrl = null;
byte[] buf = new byte[2048];
int size = 0;
try {
URL url = new URL(filePath);
if (url != null) {
httpUrl = (HttpURLConnection) url.openConnection();
}
if (httpUrl != null) {
httpUrl.connect();
if (httpUrl.getInputStream() != null)
bis = new BufferedInputStream(httpUrl.getInputStream());
}
if (filePath.lastIndexOf("/") != -1) {
String fileName = filePath
.substring(filePath.lastIndexOf("/") + 1);
String extName = fileName.substring(fileName.lastIndexOf("."));
if (!extName.equalsIgnoreCase(".jpg")
&& !extName.equalsIgnoreCase(".jpeg")
&& !extName.equalsIgnoreCase(".gif")
&& !extName.equalsIgnoreCase(".bmp")
&& !extName.equalsIgnoreCase(".png")) {
}
File dir = new File("D://");
if (!dir.exists()) {
dir.mkdirs();
}
fos = new FileOutputStream(dir.getPath());
if (fos != null) {
if (bis != null) {
while ((size = bis.read(buf)) != -1) {
fos.write(buf, 0, size);
}
}
fos.flush();
}
}
} catch (Exception e) {
}
try {
if (fos != null)
fos.close();
if (bis != null)
bis.close();
if (httpUrl != null)
httpUrl.disconnect();
} catch (Exception e) {
}
}

热点排行