从互联网保存图片到本地

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) {
}
}

你可能感兴趣的:(互联网)