java基础:9.3 从web上读取数据

除开从电脑中的本地文件或者文件服务器中读取数据,如果知道Web 上文件的URL(Uniform Resource Locator, 统一资源定位器,即为Web 上的文件提供唯一的地址),也可以从Web 上访问数据。例如,www.google.com/index.html 是位于Google Web 服务器上的文件index.html的URL。当在一个Web 浏览器中输入URL 之后,Web 服务器将数据传送给浏览器,浏览器则将数据渲染成图形。

为了读取一个文件,首先要使用:java.net.URL 类的这个构造方法,为该文件创建一个URL 对象。

如果URL 字符串出现语法错误的话,将会有一个MalformedURLException 被抛出。例如,URL 字符串“http:www.google.com/index.html” 将会引起Mai formedURLException 运行错误,因为在冒号(:)之后要求带有双斜杠(//)。注意,要让URL 类来识别一个有效的URL, 前缀http:// 是必需的。

创建一个URL 对象后,可以使用URL 类中定义的openStream()方法来打开输入流和用输人流创建如下Scanner 对象。

程序:提示用户输人一个URL, 然后显示文件的大小。

import java.util.Scanner;

public class RromURL {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		System.out.println("enter a URL(such as:http://wwww.xxxx.com):");
		String URLString = new Scanner(System.in).next();
		
		try {
			java.net.URL url = new java.net.URL(URLString);
			int count = 0;
			Scanner input = new Scanner(url.openStream());
			while(input.hasNext()) {
				String line = input.nextLine();
				count += line.length();
			}
			
			System.out.println("the file sieze is "+ count + " characters");
		}
		
		catch(java.net.MalformedURLException ex) {
			System.out.println("Invalid URL");
		}
		catch(java.io.IOException ex) {
			System.out.println("I/O error : no such file");
		}
	}

}

结果:

原文地址:https://www.cnblogs.com/l20902/p/10610936.html