1. 简单谈下你对编译时异常和运行时异常的理解
答:异常是程序本身可以处理的异常问题,与错误是两种不同的东西,错误是程序自身无法处理的问题
- 编译时异常:调用的方法在底层代码里往上抛出异常,就要在代码里解决;在语法上来说,必须处理,如果不处理无法正常编译下去
- 运行时异常:底层源代码出现判断:若条件不成立或者逻辑出现错误,就创建异常对象,然后抛出。系统自身抛出,就不会影响编译(运行时异常举例:数组越界;除数为0)
出现异常时的解决办法:要么用try-catch捕获他这个异常;要么用throws往上层抛
2.编写代码采集腾讯网的源代码
package com.Tencent.gatherInformation.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* <p>Title: GatherInformation</p>
* <p>Description: 编写代码采集腾讯网的源代码 </p>
* @author Administrator
* @date 2018年12月5日
* @version 1.0
*/
public class GatherInformation {
private static void getTencentCode(String TencentURL, String fileDir) {
InputStreamReader isr = null;
BufferedReader br = null;
File file = null;
FileWriter fw = null;
try {
//建立链接,初始化一个URL对象
URL url = new URL(TencentURL);
//访问链接,初始化一个URLConnection对象
URLConnection urlc = url.openConnection();
//建立输入流,从腾讯网里读取源代码
isr = new InputStreamReader(urlc.getInputStream());
//加入缓存机制,提高读取速度
br =new BufferedReader(isr);
file = new File(fileDir);
//如果文件存在,则删除
if (file.exists()) {
file.delete();
}
//创建文件
file.createNewFile();
//以写的方式打开文件
fw = new FileWriter(file);
//读取腾讯网里的每一行代码,直至为空
while((br.readLine()) != null) {
//写入文件
fw.write(br.readLine() + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
//关闭
if (fw != null) {
fw.close();
fw = null;
}
if (br != null) {
br.close();
br = null;
}
if (isr != null) {
isr.close();
isr = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//主函数
public static void main(String[] args) {
//类方法
GatherInformation.getTencentCode("https://www.qq.com/", "C:\\Users\\Administrator\\Desktop\\Demo.txt");
//getTencentCode("https://www.qq.com/", "C:\\Users\\Administrator\\Desktop\\Demo.txt");
}
}