Java网络编程值URL

各种路径的获取方式

package com.song._14URL;

import java.io.File;

public class URLPath {
	public static void main(String[] args) {
		System.out.println("1--"+Thread.currentThread().getContextClassLoader()
				.getResource(""));


		System.out.println("2--"+URLPath.class.getClassLoader().getResource(""));


		System.out.println("3--"+ClassLoader.getSystemResource(""));
		System.out.println("4--"+URLPath.class.getResource(""));
		System.out.println("5--"+URLPath.class.getResource("/"));
		// Class文件所在路
		System.out.println("6--"+new File("/").getAbsolutePath());
		System.out.println("7--"+System.getProperty("user.dir"));
		System.out.println("8--"+new File("C:\\ccc\\123").getParent()); // 获取上一级目录
	}
}

输出:	1--file:/F:/Java/workspace/workspace3.7.2_1/Stu/bin/
	2--file:/F:/Java/workspace/workspace3.7.2_1/Stu/bin/
	3--file:/F:/Java/workspace/workspace3.7.2_1/Stu/bin/
	4--file:/F:/Java/workspace/workspace3.7.2_1/Stu/bin/com/song/_14URL/
	5--file:/F:/Java/workspace/workspace3.7.2_1/Stu/bin/
	6--F:\
	7--F:\Java\workspace\workspace3.7.2_1\Stu
	8--C:\ccc

网络编程的目的是直接或间接地通过网络协议与其他计算机进行通讯。目前较为流行的编程模型是客服机/服务器(C/S)结构。网络有一个TCP/IP的是传输层和TCP

网络有一个TCP/IP的是传输层和TCP和UDP两个协议。

  • TCP是Transfer Control protocol(传输控制协议)的简称,是一种面向连接的保证可靠传输的协议。送发放和接收方的成对的两个socket之间必须建立连接,以便进行通信。
  • UDP是User Datagram Protocol(用户数据包协议)的简称,是一种无连接的协议,每个数据报都是一个独立的信息,包括完成的源地址或目的地址,它在网络上以任何可能的路径传往目的地,因此能否到达目的地,到达目的地的时间以及内容的正确性都是不能被保证。
  • 网络中有一个重要的概念是URL,有了URL用户可以访问网络资源。

1.1 URL是什么

URL(Uniform Resource Locator)是一致资源定位器的简称,它表示Internet上某一资源的地址。通过URL可以访问Internet上的各种网络资源,如最常见的WWW、FTP站点。

为了能够识别网络上的每个设备,一个设备都会有一个唯一标识的数字标识,就是IP地址。在计算机网络中,现在命名IP地址的规定是IPv4协议,该协议规定每个IP地址由个0~255之间的数字组成,如10.0.125.80.每个接入网络的计算机都有唯一的IP地址,这个IP地址可能是固定的,如网络上各种各样的服务器,有可以是动态的,如理,使用ADSL拨号上网的宽带用户,无论以何种方式获得或者是否是固定的,每个计算机在联网以后都拥有一个唯一合法地IP地址,就像每个手机号码一样。但由于IP地址不容易被记住,又创造了另外一个概念——域名(Domain Name),如baidu.com等。一个IP地址可以对应多个域名,一个域名只能对应一个IP地址。

1.2 URL的组成

	URL的组成:protocol://resourceName


  • 协议名(protocol)指明获取资源所使用传输协议,如http、ftp、gopher、file等
  • 资源名(resourceName)则应该是资源的完地址,包括主机名、端口号、文件名或文件内部的一个引用。

协议名://主机名——http://www.sun.com/
协议名://机器名+文件名——http://www.sun.com/test.jsp
协议名://机器名+端口号+文件名+内部引用——http://www.sun.com:80/test/network#BPTTOM

1.3 创建URL

为了表示URL,java.net中实现了类URL。初始化一个URL对象如下:

1.public URL(String spec)——通过一个表示URL地址的字符串可以构造一个URL对象。
	URL urlBase = new URL("http://www.sun.net/');
2.public URL(URL context,String spec)——通过基URL和相对URL构造一个URL对象
	URL netsun= new URL("http://www.sun.com/');
	URL indexsun = new URL(netsun,"index.html");
3.public URL(String protocol,String host,String file)
	new URL("http","www.sun.com","/pages/Gamelan.net.html");
4.public URL(String protocol,String host,int port,String file)
	new URL("http","www.sun.com",80,"/pages/Gamelan.net.html");

1.4解析URL

URL类的常用方法:

 String	getAuthority()		 获取此 URL 的授权部分。权限信息
 Object	getContent() 		 获取此 URL 的内容。
 String	getFile() 		 获取此 URL 的文件名。
 String	getHost() 		 获取此 URL 的主机名(如果适用)。
 String	getPath() 	         获取此 URL 的路径部分。
 int	getPort()		 获取此 URL 的端口号。
 String	getProtocol()		 获取此 URL 的协议名称。
 String	getQuery()		 获取此 URL 的查询部分。
 String	getRef()		 获取此 URL 的锚点(也称为“引用”)。
 String	getUserInfo()		 获取此 URL 的 userInfo 部分。
			URL url = new URL("http://www.baidu.com:80/test/network#BPTTOM");
			String host = url.getHost();
			String author = url.getAuthority();
			Object content = url.getContent();
			String file = url.getFile();
			String path = url.getFile();
			int port = url.getPort();
			String protocol = url.getProtocol();
			String query = url.getQuery();
			String ref = url.getRef();
			String userInfo = url.getUserInfo();
			System.out.println("主机是:"+host);
			System.out.println("权限是:"+author);
			System.out.println("内容是:"+content);
			System.out.println("文件是:"+file);
			System.out.println("路径:"+path);
			System.out.println("端口号:"+port);
			System.out.println("协议:"+protocol);
			System.out.println("查询信息:"+query);
			System.out.println("相对位置:"+ref);
			System.out.println("使用者信息:"+userInfo);
输出结果:

主机是:www.baidu.com
权限是:www.baidu.com:80
内容是:sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@5c647e05
文件是:/test/network
路径:/test/network
端口号:80
协议:http
查询信息:null
相对位置:BPTTOM
使用者信息:null
使用URL的方法 openStream()读取网络上的资源,openStream()与指定的URL建立连接返回InputStream类对象以从这一连接中读取数据。

			//读取网络资源
			URL url = new URL("http://www.sohu.com");
			BufferedReader buf   = new BufferedReader(new InputStreamReader(url.openStream()));
			String line = null;
			while ((line=buf.readLine())!=null) {
				System.out.println(line);
			}


使用URL和多线程下载远程资源文件。

package com.song._14URL;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 使用URL和多线程下载远程资源文件。
 */
public class DownloadSkip implements Serializable {
	private int id;
	private String address;// 下载地址
	private String fileName;// 文件名
	private int pos;// 文件位置
	private int fileSize;// 文件大小
	private DownloadThread thread;
	private boolean finished;// 是否下载成功

	public DownloadSkip(String _address, String _fileName) throws IOException {
		this.address = _address;
		this.fileName = _fileName;
		this.fileSize = fetchFileSize();
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getPos() {
		return pos;
	}

	public void setPos(int pos) {
		this.pos = pos;
	}

	public synchronized boolean isFinished() {
		return finished;
	}

	public synchronized void setFinished(boolean _finished) {
		this.finished = _finished;
	}

	public static void main(String[] args) {
		try {
			// "http://apache.fayea.com/apache-mirror/tomcat/tomcat-6/v6.0.37/bin/apache-tomcat-6.0.37.zip";
			String s = "http://eclipse.stu.edu.tw/technology/babel/babel_language_packs/R0.14.1/luna/BabelLanguagePack-eclipse-zh_4.4.0.v20161126102919.zip";
			DownloadSkip d = new DownloadSkip(s, "D:/"
					+ s.substring(s.lastIndexOf("/")));
			d.startDownload();
		} catch (MalformedURLException e) {
			System.out.println("URL错误");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("IO错误");
			e.printStackTrace();
		}
	}

	public static String get(int i) {
		if (i < 9) {
			return "00" + (i + 1) + ".png";
		}
		return "0" + (i + 1) + ".png";
	}

	private int fetchFileSize() throws IOException {
		URL url = new URL(address);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		return conn.getContentLength();
	}

	/**
	 * 开始下载
	 */
	public void startDownload() {
		// 启动一个线程下载
		if (thread == null) {
			thread = new DownloadThread();
			thread.start();
		}
	}

	public static void downloadSkip(String path) throws IOException {
		String filename = path.substring(path.lastIndexOf("/" + 1));
		URL url = new URL(path);
		// 只对http协议有效
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 不希望从第一个字节开始读取,希望指定的字节开始读取
		conn.setRequestProperty("RANGE", "bytes=100-");// RANGE指的是范围,从第一百个字节开始读取
		int filezie = conn.getContentLength();// 获取远程文件的大小
	}

	private class DownloadThread extends Thread {
		private boolean stop;

		public synchronized boolean isStop() {
			return stop;
		}

		public synchronized void setStop(boolean _stop) {
			this.stop = _stop;
		}
		@Override
		public void run() {
			long start = System.currentTimeMillis();
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			// 下载
			try {
				URL url = new URL(address);
				// 只对http协议有效
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setRequestProperty("RANGE", "byes=" + pos + "-");
				InputStream in = conn.getInputStream();
				FileOutputStream fos = new FileOutputStream(fileName, true);
				bis = new BufferedInputStream(in);
				bos = new BufferedOutputStream(fos);

				int b = -1;
				// byte[] buf = new byte[in.available()];
				while ((b = bis.read()) != -1 && !isStop()) {
					bos.write(b);
					setPos(getPos() + 1);
				}
				if (getPos() == fileSize) {
					setFinished(true);
				}
			} catch (MalformedURLException e) {
				System.out.println("URL异常...");
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				System.out.println("文件找不到异常...");
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {

				try {
					if (bos != null)
						bos.close();
					if (bis != null)
						bis.close();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			long end = System.currentTimeMillis();
			System.out.println("总共花了:" + (end - start) / 1000 + "秒");
		}
	}
}









































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值