본문 바로가기

Java SE/URLConnection 03

URLConnection 03

/* URL, URLConnection 을 이용한 웹상의 파일(HTML, Image, swf 등)복사해 오기.
* URL클래스를 이용하여 URLConnection객체를 얻고, URLConnection.getInputStream()을 호출하면,
* InputStream 을 얻을 수 있다. 이 스트림을 이용하여 Google.co.kr의 첫 페이지의 구글로고 이미지를
* logo.gif으로 저장해 보세요. 이번에는 ByteArrayOutputStream을 반드시 활용하여 작성해 보세요.
*/

import java.io.*;
import java.net.*;

class  URLConnectionTest02 {
 public static void main(String[] args) throws IOException  {

  URL url = new URL("http://img0.gmodules.com/ig/f/oKstlUEg20s/intl/ALL_kr/logo.gif");
  URLConnection conn = url.openConnection();

  InputStream in = conn.getInputStream();

  BufferedInputStream bin = new BufferedInputStream(in);
  byte[] buf = new byte[1024];
 
  ByteArrayOutputStream bao = new ByteArrayOutputStream();
 
  int read = 0;
  while((read=bin.read(buf, 0, buf.length))!= -1) {
   bao.write(buf, 0, read);
  }
  FileOutputStream fos = new FileOutputStream("logo.gif");
  fos.write(bao.toByteArray());

  bin.close();
  bao.close();
  fos.close();
 }
}