Java网络编程之URL

来源:互联网 发布:淘宝怎么合并订单 编辑:程序博客网 时间:2024/05/21 07:54
import java.io.BufferedInputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.Reader;import java.net.MalformedURLException;import java.net.URL;public class URLTest {    public static void main(String[] args) {        // downloadImg("http://localhost:8080/image/tu1.jpg");        downloadHtml("http://localhost:8080");        testProcotol2();    }    /**     * 获取虚拟机支持的协议     *      * @param url     */    public static void testProtocol(String url) {        try {            URL u = new URL(url);            System.out.println(u.getProtocol() + " is supported");        } catch (MalformedURLException e) {            e.printStackTrace();        }    }    /**     * 相对URL     */    public static void testProcotol2() {        String baseUrl = "http://localhost:8080/image/tu1.jpg";        try {            URL u = new URL(baseUrl);            URL u2 = new URL(u, "tu2.jpg");// 将文件名从url中去掉,追加新的文件名tu2.jpg            System.out.println(u2.getProtocol() + " is supported,"                    + u2.getFile());        } catch (MalformedURLException e) {            e.printStackTrace();        }    }    /**     * 读取URL中的流下载图片     *      * @param url     */    public static void downloadImg(String url) {        try {            URL u = new URL(url);            InputStream ins = u.openStream();            File f = new File("/home/archermind/1.jpg");            OutputStream fout = new FileOutputStream(f);            int ch = 0;            while ((ch = ins.read()) != -1) {                fout.write(ch);            }            fout.flush();            fout.close();            ins.close();        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    /**     * 下载一个web页面     *      * @param url     */    public static void downloadHtml(String url){        InputStream in = null;        OutputStream out = null;        try {            URL u = new URL(url);            in = u.openStream();            in = new BufferedInputStream(in);            Reader r = new InputStreamReader(in);            File f = new File("/home/archermind/index.html");            out = new FileOutputStream(f);            int c;            while((c=r.read())!=-1){                System.out.print((char)c);                out.write(c);            }            out.flush();        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally{            try {                if(in!=null){                    in.close();                }                if(out!=null){                    out.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }}
0 0
原创粉丝点击