java学习之url

 package com.gh.URL;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
/**
* 利用url下载文件
*
* @author ganhang
*
*/
public class URLDemo {
public static void main(String[] args) {
try {
URL url=new URL("http://localhost:8080/hehe/1.jpg");//tomcat启动一个服务器
//System.out.println("内容:"+url.getContent());//获得内容
System.out.println("主机名:"+url.getHost());//获得主机名
System.out.println("路径:"+url.getPath());//获得路径
System.out.println("端口号:"+url.getPort());//获得端口号
System.out.println("协议:"+url.getProtocol());
URLConnection conn= url.openConnection();//获得连接对象
//获得连接对象的字节缓存输入流
//上传用getOutputStream()
BufferedInputStream bis= new BufferedInputStream(conn.getInputStream());
//下载到当前目录的缓存输出流
BufferedOutputStream bos =new BufferedOutputStream(new FileOutputStream("1.jpg"));
int len =-1;
byte[] b =new byte[1024];
while((len=bis.read(b))!=-1){
bos.write(b,0,len);
bos.flush();
}
bis.close();
bos.close();
System.out.println("下载成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
上一篇:xshell配色Solarized Dark


下一篇:常用Petri网模拟软件工具简介