Java로 URL 읽어오기

Text

 

import java.net.URL;
import java.net.URLConnection;
import java.net.MalformedURLException;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

public class URLConn{
    public static void main(String args[]){
        URL url;//URL 주소 객체
        URLConnection connection;//URL접속을 가지는 객체
        InputStream is;//URL접속에서 내용을 읽기위한 Stream
        InputStreamReader isr;
        BufferedReader br;
       
        try{
            //URL객체를 생성하고 해당 URL로 접속한다..
            url = new URL(args[0]);
            connection = url.openConnection();

            //내용을 읽어오기위한 InputStream객체를 생성한다..
            is = connection.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);

            //내용을 읽어서 화면에 출력한다..
            String buf = null;
            while(true){
                buf = br.readLine();
                if(buf == null) break;
                System.out.println(buf);
            }
        }catch(MalformedURLException mue){
            System.err.println("잘못되 URL입니다. 사용법 : java URLConn http://hostname/path]");
            System.exit(1);
        }catch(IOException ioe){
            System.err.println("IOException " + ioe);
            ioe.printStackTrace();
            System.exit(1);
        }
    }
};

 

Binary

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;

public class TestURL {
   
    public static void main(String[] args) throws Exception {
       
        String strUrl = "";
        String strOut = "";
       
        //FTP
        strUrl = "ftp://jupiter:tjsdud00@www.zlbl.com/public_html/wp/wp-content/uploads/2006/10/boss_20061002_01.jpg";
        strOut = "c:/boss_20061002_01.jpg";
       
        //HTTP
        //strUrl = "http://www.seonyoung.pe.kr/wp/wp-content/uploads/2006/10/boss_20061002_01.jpg";
        //strOut = "c:/boss_20061002_01.jpg";
               
        URL url = new URL(strUrl);
        URLConnection con = url.openConnection();
        BufferedInputStream in = new BufferedInputStream(con.getInputStream());
        FileOutputStream out = new FileOutputStream(strOut);
       
        int i = 0;
        byte[] bytesIn = new byte[1024];
        while ((i = in.read(bytesIn)) >= 0) {
            out.write(bytesIn, 0, i);
        }
       
        out.close();
        in.close();
        System.out.println("Completed!");
    }
}