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和==的区别 |