Java URL 사용법


/**
 * 웹페이지 가져오기
 * URL과 저장할 파일을 입력하면
 * 사이트 내용을 가지고 와서 파일에 저장함
 *
 */
public class WebSpider {
    public static void main(String[] args){
        if(args.length != 2){
             System.out.println("사용법" : java WebSpider URL filename");
             System.exit(1);
        }
        URL url = null;
        try{
            url = new URL(args[0]);
        }catch(MalformedURLException e1){
            System.out.println("잘못된 URL 형식입니다.");
            System.out.println(e1);
            System.exit(1);
        }
  
        FileOutputStream fos = null;
        try{
            InputStream in = url.openStream();
            fos = new FileOutputStream(args[1]);
  
            byte[] buffer = new byte[512];
            int readCount = 0;
   
            System.out.println("읽어 오기 시작함 ...");
            while((readCount = in.read(buffer)) != -1){
                fos.write(buffer,0,readCount);
            }
            System.out.println(args[1] + " 파일에 모두 저장했습니다.");
        }catch(Exception ex){
            System.out.println(ex);
        }finally{
            try{
                if(fos != null) fos.close();
            }catch(Exception e){}
        }
    }
}

댓글

이 블로그의 인기 게시물

How to split a list into chunks of 100 items in JavaScript, 자바스크립트 리스트 쪼개기

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

To switch to a specific tag in a Git repository