URL编程

1 统一资源定位符,一个URL的对象,对应互联网上的一个对象,我们可以通过URL

对象调用其相应的方法,将其资源下载

package lianxi1;

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

import org.junit.Test;

public class TestURL {
@Test
   public void test() throws IOException{
    URL url = new URL("http://127.0.0.1:8080/manager/hello.txt");
    System.out.println(url.getPath());
    System.out.println(url.getPort());
    //1.读取服务器的资源
    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.print(str);
    }
    is.close();
    //2.如果有数据输出
    URLConnection uc = url.openConnection();
    InputStream is2 = uc.getInputStream();
    FileOutputStream os = new FileOutputStream(new File("welcome.txt"));
    byte[] b2 = new byte[20];
    int len2;
    while((len2=is2.read(b2))!=-1){
        os.write(b2,0,len2);
    }
    os.close();
    is2.close();
}
}
原文地址:https://www.cnblogs.com/yjtm53/p/4168189.html