Board logo

标题: Java读取网络照片的方法 [打印本页]

作者: qingqing3721    时间: 2011-8-18 18:29     标题: Java读取网络照片的方法

importjava.io.BufferedInputStream;   importjava.io.BufferedOutputStream;   importjava.io.FileOutputStream;   importjava.HttpURLConnection;   importjava.URL;   importjava.URLConnection;   /*.*读取网络照片,保存到本地   **/   publicclassGetUrlImg{   publicstaticvoidgetUrlImg(StringURLName,Stringtarget)throwsException{//URLName照片地址   //target本地地址   intHttpResult=0;//服务器前往的状态   URLurl=newURL(URLName);//创立URL   URLConnectionurlconn=url.openConnection();//试图连接并取得前往状态码urlconn.connect();   HttpURLConnectionhttpconn=(HttpURLConnection)urlconn;   HttpResult=httpconn.getResponseCode();   System.out.println(HttpResult);   if(HttpResult!=HttpURLConnection.HTTP_OK)//不等于HTTP_OK说明连接不成功System.1out.print("fail");   else{   intfilesize=urlconn.getContentLength();//取数据长度System.out.println(filesize);   BufferedInputStreambis=newBufferedInputStream(urlconn.getInputStream());   BufferedOutputStreambos=newBufferedOutputStream(newFileOutputStream(target));   byte[]buffer=newbyte[1024];//创立寄存输出流的缓冲   intnum=-1;//读入的字节数   while(true){   num=bis.read(buffer);//读入到缓冲区   if(num==-1){   bos.flush();   break;//曾经读完   }   bos.flush();   bos.write(buffer,0,num);   }   bos.close();   bis.close();   }   }   publicstaticvoidmain(String[]args)throwsException{   GetUrlImg.getUrlImg




欢迎光临 编程开发论坛 (http://bbs.lihuasoft.net/) Powered by Discuz! 6.0.0