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){}
        }
    }
}

댓글 없음:

댓글 쓰기

깔끔 테마. Powered by Blogger.