네트워크 사진 다운로드

package com.home;

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 DownloadImage {
	public DownloadImage() {
		try {
			getImage();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new DownloadImage();
	}

	/**
	 *       
	 * 
	 * @throws Exception
	 */
	public void getImage() throws Exception {
		//   url  
		String urlpath = "http://pica.nipic.com/2008-05-23/200852381811521_2.jpg";
		//   URL  ,    
		URL url = new URL(urlpath);
		//   HttpURLConnection  
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		//       
		conn.setRequestMethod("GET");
		//       
		conn.setConnectTimeout(6 * 1000);
		//     
		if (conn.getResponseCode() == 200) {
			//            ,         
			InputStream inputStream = conn.getInputStream();
			//     
			byte[] data = readInStream(inputStream);
			//       
			File file = new File("C:/image.jpg");
			//          
			FileOutputStream outputStream = new FileOutputStream(file);
			//                        
			outputStream.write(data);
			//      
			outputStream.close();
		}

	}

	/**
	 *         
	 * 
	 * @param inputStream
	 * @return
	 * @throws Exception
	 */
	public byte[] readInStream(InputStream inputStream) throws Exception {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		//      
		byte[] buffer = new byte[1024];
		//         
		int length = -1;
		while ((length = inputStream.read(buffer)) != -1) {
			//            
			byteArrayOutputStream.write(buffer, 0, length);
		}
		//      
		byteArrayOutputStream.close();
		//      
		inputStream.close();
		//             
		return byteArrayOutputStream.toByteArray();
	}
}

좋은 웹페이지 즐겨찾기