URL downloading images of input and output streams

Use Java input and output streams can download pictures from the Internet to their own

Help you better learn the input and output streams

Which is quite comprehensive comments

Thank Ferris

package com.Grap;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class Download {
public static void main(String[] args) throws Exception {
//获取图片URL地址
String s1="https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=3284403661,3037645860&fm=173&app=25&f=JPEG?w=218&h=146&s=7F200FC3424318EC643CD59E0300A013";
URL url=new URL(s1);
HttpURLConnection con=(HttpURLConnection) url.openConnection();//打开链接方式
con.setRequestMethod ( "GET"); // in a GET request for connection
con.setConnectTimeout (5 * 1000); // Set the connection time is five seconds
InputStream is = con.getInputStream (); // get image input stream
byte [ ] = readInputStream BYT (IS);
// file = new new Image file ( "G: \\ image.jpg");
the OutputStream new new OS = a FileOutputStream ( "G: \\ image.jpg"); // Create a file output flow for storing image position
os.write (byt); // write image
// is.close ();
os.close ();
}
public static byte [] readInputStream (the InputStream IS) throws Exception {
ByteArrayOutputStream outsream = new new ByteArrayOutputStream (); // Create a byte array output stream
byte [] b = new byte [ 10240000]; // create and set the size of the byte array
int len = 0; // set the image storage starting position
while ((len = is. read (b)) = - 1 ) {// read the image input stream end unread!
outsream.write (b, 0, len); // b side of the array of bytes read
}
outsream.close ();
return outsream.toByteArray (); // returns a byte array
}

}




This is the download of local pictures. ,

Probably it is like this!


Published 19 original articles · won praise 58 · views 50000 +

Guess you like

Origin blog.csdn.net/cyg_l02/article/details/80331321