HelloWorld系列之--------手动下载网络页面

6 篇文章 0 订阅
4 篇文章 0 订阅
    在浏览器地址栏输入要打开的页面地址,点击连接就可以获得所要的页面,那么浏览器是如何工作的呢,这里我用java模拟了一个浏览器程序把页面内容下载到本地文件中。

代码如下:
package web;

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

public class URLWebTester {
	public static void main(String[] args) throws Exception {
		//要下载的页面
		URL url = new URL("http://www.ouyaya.com/");
		//打开连接
		URLConnection urlConnection = url.openConnection();
		urlConnection.connect();
		
		//创建存储页面的本地文件
		File file = new File("e://ouyaya.html");
		if(!file.exists()) {
			file.createNewFile();
		}
		
		//输入到文件的输出流
		FileOutputStream fos = new FileOutputStream(file);
		//用于读取文件的输入流
		InputStream inputStream = urlConnection.getInputStream();
		BufferedInputStream bis = new BufferedInputStream(inputStream);
		
/*		String tempString = null;
		while((tempString = br.readLine()) != null) {
			fos.write(tempString);
			fos.write("\r\n");
		}*/
		//下载页面到本地文件
		byte[] buffer = new byte[1024];
		int length = -1;
		
		while((length = bis.read(buffer)) != -1) {
			fos.write(buffer, 0, length);
		}
		
		//关闭流对象
		fos.close();
		bis.close();
		inputStream.close();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值