Java reads the image from the network and saves it to the local instance

  • 2020-07-21 07:55:59
  • OfStack

This article shares the specific code for Java to read pictures from the network and save them locally for your reference. The specific content is as follows


package getUrlPic;

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

public class GetUrlPic {
 
 public static void main(String[] args) throws Exception { 
  //new1 a URL object  
  URL url = new URL("http://www.gz135.cn/data/attachment/forum/201702/13/165605xyayykq5vy4h81vy.jpg"); 
  // Open the link  
  HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
  // Set the request mode to "GET" 
  conn.setRequestMethod("GET"); 
  // The timeout response time is 5 seconds  
  conn.setConnectTimeout(5 * 1000); 
  // Get the image data from the input stream  
  InputStream inStream = conn.getInputStream(); 
  // Pictographic 2 Base data, to 2 The data obtained by base encapsulation is universal  
  byte[] data = readInputStream(inStream); 
  //new1 File object to save the image, default to save the current project root directory  
  File imageFile = new File("pic20170419.jpg"); 
  // Create an output stream  
  FileOutputStream outStream = new FileOutputStream(imageFile); 
  // Write data  
  outStream.write(data); 
  // Close the output stream  
  outStream.close(); 
 } 
 public static byte[] readInputStream(InputStream inStream) throws Exception{ 
  ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
  // create 1 a Buffer string  
  byte[] buffer = new byte[1024]; 
  // The length of the string per read, if -1 Represents that all readings have been completed  
  int len = 0; 
  // use 1 One input stream from buffer Read the data out  
  while( (len=inStream.read(buffer)) != -1 ){ 
   // Use the output stream to buffer To write data, the intermediate parameter represents where to start reading, len Represents the length of the read  
   outStream.write(buffer, 0, len); 
  } 
  // Close the input stream  
  inStream.close(); 
  // the outStream The data is written to memory  
  return outStream.toByteArray(); 
 } 

}

Related articles: