Notice
Recent Posts
Recent Comments
Link
관리 메뉴

설.현.아빠

[Java2] URL을 화일로 저장하는 예제 입니다.. 본문

안드로이드/File

[Java2] URL을 화일로 저장하는 예제 입니다..

설.현.아빠 2011. 2. 11. 10:26



/**
 * By cozyhill
 */
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class DownLoadURL {
 
 public String url;
 public String path; 
 
 public DownLoadURL(String url, String path){
  this.url = url;
  this.path = path;
 }
 
 public void executeDownload(){  
  InputStream is = null;
  URL address;
  try {   
   address = new URL(url);
   System.out.println("########## URL 생성");
  } catch (MalformedURLException e) {
   System.out.println("########## URL 형식이 잘못 되었습니다.");
   e.printStackTrace();
   return;
  } 
  
  URLConnection httpConn;
  try {
   httpConn = address.openConnection();
   System.out.println("########## 서버접속");
  } catch (IOException e) {
   System.out.println("########## 서버에 연결 할 수 없습니다");
   e.printStackTrace();
   return;
  } 
  httpConn.setDoOutput(true);
  try {
   is =  httpConn.getInputStream();
   System.out.println("########## 화일다운로드");
   saveFile(is);
  } catch (IOException e) {
   System.out.println("########## 화일이 없습니다.");
   e.printStackTrace();
  }finally{
   if(is!=null){
    try {
     is.close();
    } catch (IOException e) {     
     e.printStackTrace();
    }
   }
  }
 } 
 public boolean saveFile( InputStream inputstream){
   byte abyte0[] = new byte[4096];
   boolean flag = true;
   FileOutputStream outputStream = null;
  try {
   outputStream = new FileOutputStream(path);
   int i;
   while((i = inputstream.read(abyte0)) != -1){ 
     outputStream.write(abyte0, 0, i);
    }
   System.out.println("########## 화일저장");
  } catch (FileNotFoundException e1) {
   flag = false;
   System.out.print("########## 저장경로가 없습니다");
   e1.printStackTrace();   
  }catch (IOException e) {
   flag = false;
   System.out.print("########## 저장중 오류가 발생했습니다.");
   e.printStackTrace();   
  }finally{
   if(outputStream!=null){
    try {
     outputStream.close();
    } catch (IOException e) {     
     e.printStackTrace();
    }
   }
  }
    
  return flag;
 }
 
 public static void main(String[] args){
  System.out.println("#### 다운로드 시작 ####");
  DownLoadURL down = new DownLoadURL("http://www.jlancer.net/board/images/ico_diskett.gif", "C:\\test\\test.gif");
  down.executeDownload();
  System.out.println("#### 다운로드 끝 ####");
 }
}



Comments