a我考网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 97|回复: 0

[基础知识] JAVA基础:java读取网络照片

[复制链接]
发表于 2012-8-4 12:37:27 | 显示全部楼层 |阅读模式
import java.io.BufferedInputStream;   import java.io.BufferedOutputStream;; j# _* h; J: f# B) ~+ Q
  import java.io.FileOutputStream;; \. A6 _  }) y; `- M  _
  import java.net.HttpURLConnection;/ e2 H9 R0 E+ a. N+ r
  import java.net.URL;( t$ Q3 ]2 g! ~) \3 r: N* u
  import java.net.URLConnection;
' s4 K' q' i! A) n/ b! i  /*. *读取网络照片,保存到本地
2 R* i8 W8 {4 N/ y7 w; x  N- r  * */
% q1 `, y& B; Q* w  public class GetUrlImg {
/ Q: w1 u- w- ?6 h! ^+ l4 a  public static void getUrlImg(String URLName,String target) throws Exception {//URLName照片地址
7 m- w7 w- n1 H  // target本地地址
" }5 E0 \" X$ a0 ^  int HttpResult = 0; //服务器返回的状态0 s5 y8 L  I$ g- [
  URL url = new URL(URLName); //创建URL
/ S9 _; G" Q9 ]$ O) A+ Z3 ^  URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码urlconn.connect();' X0 R5 c* U7 j
  HttpURLConnection httpconn = (HttpURLConnection) urlconn;
9 {  X/ M+ z& U; L  HttpResult = httpconn.getResponseCode();
5 [# [# k5 g- `0 `, w. O6 U  System.out.println(HttpResult);
0 {+ t, i3 j" `  F# f% j- l0 L' ?  if (HttpResult != HttpURLConnection.HTTP_OK) // 不等于HTTP_OK说明连接不成功System.out.print("fail");
( T& x# K" G* M. I4 I$ L- k% O8 `  else {
% P* G# D; V4 e  int filesize = urlconn.getContentLength(); // 取数据长度System.out.println(filesize);
  C' ^6 s& X6 R  BufferedInputStream bis=new BufferedInputStream(urlconn.getInputStream());7 B# k0 E+ Z/ {& }
  BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(target));
$ O0 D8 u7 J0 H$ q% p4 L  byte[] buffer = new byte[1024]; //创建存放输入流的缓冲! \9 b6 i1 n6 L# A& e
  int num = -1; //读入的字节数
% O9 }5 |9 V  |) g0 E  while (true) {# |0 g/ K- n' u$ O8 {/ K: D
  num = bis.read(buffer); // 读入到缓冲区/ |3 [% r  [9 ^
  if (num ==-1){
* F* p2 ?" H$ j+ d* v8 ]9 @  X  bos.flush();' R2 G- l( w0 }
  break; //已经读完
  t. [* \0 q1 I  }
' q: D" u5 @5 U7 j9 g& c" T+ y2 f# n6 [  bos.flush();) A7 q( p1 T9 n8 d6 p
  bos.write(buffer,0,num);
0 Y( Y6 o) n4 Y7 O3 @  }
! l! M3 l' \% \, @  bos.close();- e4 D4 K; Y1 T' z% B' H3 P2 @
  bis.close();
; a# |! J3 D. n6 a/ }2 S0 `  }
* ]# I7 J+ O9 P. h' c  }
  B# K% M/ }7 n5 i  public static void main(String[] args) throws Exception{2 d! r* {& I2 t- h5 y4 A' A) C" U
  GetUrlImg.getUrlImg("java中equals和==的区别
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Woexam.Com ( 湘ICP备18023104号 )

GMT+8, 2024-5-6 15:08 , Processed in 0.173755 second(s), 21 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表