• 通过Url网络编程实现下载


    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;

    //URL:统一资源定位符,一个URL的一个对象对应互联网上的一个资源,
    //通过URL的对象调用相应方法,将此资源读取(“下载”)
    public class TestUrl {
    public static void main(String[] args) {
    //穿件一个URL对象

    try {
    URL url = new URL("http://192.168.2.106:8080/exam/helloworld.txt");//File file = new File("文件路径");
    //读取的方法
    /**
    * getProtocol 获取URL的协议
    * getHost 获取URL主机名
    * getPort 获取URL端口号
    * getPath 获取URL文件路径
    * getFile 获取URL文件名
    * getRef 获取URL在文件中的相对位置
    * getQuery 获取URL查询名
    */
    System.out.println("获取URL的协议==>"+url.getProtocol());
    System.out.println("获取URL主机名==>"+url.getHost());
    System.out.println("获取URL端口号==>"+url.getPort());
    System.out.println("获取URL文件路径==>"+url.getPath());
    System.out.println("获取URL文件名==>"+url.getFile());
    System.out.println("获取URL在文件中的相对位置==>"+url.getRef());
    System.out.println("获取URL查询名==>"+url.getQuery());
    //如何精服务器端的资源读取出来openStream,该方法只负责度如数据
    InputStream is = url.openStream();
    byte[] b = new byte[20];
    int len;
    //输出到控制台
    while((len = is.read(b)) != -1){
    String str = new String(b,0,len);
    System.out.println(str);
    }

    //如果有数据输入,又有输出,则考虑用URLConnection
    //保存到本地文件
    URLConnection urlConn = url.openConnection();
    InputStream is1 = urlConn.getInputStream();
    FileOutputStream fos = new FileOutputStream(new File("abc.txt"));
    byte[] b1 = new byte[20];
    int len1;
    while((len1 = is1.read(b1)) != -1){
    fos.write(b1, 0, len1);
    }
    fos.close();
    is1.close();



    } catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }


    }
    }

  • 相关阅读:
    POJ 3292 Semi-prime H-numbers (素数筛法变形)
    POJ 1845 Sumdiv (整数拆分+等比快速求和)
    POJ 2635 The Embarrassed Cryptographer(大数求余)
    POJ 2115 C Looooops (扩展欧几里德 + 线性同余方程)
    poj3071
    poj2486
    poj1947
    POJ 1159
    POJ 1845
    poj3282
  • 原文地址:https://www.cnblogs.com/lixiuming521125/p/6428534.html
Copyright © 2020-2023  润新知