使用try_cath_finally处理流中的异常,使用Properties集合存储数据,遍历取出Properties集合中的数据
使用try_cath_finally处理流中的异常:
在jdk1.7之前使用try catch finally处理流中的异常
格式:
try{
可能会产出异常的代码
}catch(异常类变量 变量名){
异常的处理逻辑
}finally{
一定会指定的代码
资源释放
}
public class abnormal { public static void main(String[] args) { //提高变量wr的作用球,让finaLLy可以使用 //变量在定义的时候,可以没有值,但是使用的时候必须有值 //wr = new Filewriter("IOliu.txt" , true);执行失败, wr没有值, wr.cLose会报错Filewriter wr = null; FileWriter wr = null; try { //可能会产出异常的代码 wr = new FileWriter("IOliu.txt", true); for (int i = 0; i<10; i++){ wr.write("I Love you"+i+"\r\n"); } }catch (IOException e){ //异常的处理逻辑 System.out.println(e); }finally { //一定会指定的代码 //创建对象失败了, wr的默认值就是nuLl,nulL是不能调用方法的,会抛出NuLlPointerException,需要增加一个判断,不是nulL在把资源释放 if (wr!=null){ try { //wr.close方法声明抛出了IOException异常对象,所以我们就的处理这个异常对象,要么throws,要么try catch wr.close(); }catch (IOException e){ e.printStackTrace(); } } } } }
使用Properties集合存储数据,遍历取出Properties集合中的数据:
Properties集合是一个双列集合,key和vaLue黑认都是字符串
Properties集合有一些操作字符串的特有方法
object setProperty (String key,String value)调用 Hashtable 的方法 put。
string getProperty (String key)通过key找到value值,此方法相当于Nap集合中的get(key)方法
Set<String> StringPropertyWNames()返回此属性列表中的键集,其中该键及其对应情是字符串,此方法相当于Nap集合中的keyset方法
public class xiancheng { public static void main(String[] args) { Properties po = new Properties(); po.setProperty("赵丽颖","168"); po.setProperty("迪丽热巴","165"); po.setProperty("古力娜扎","160"); // } public static void show(){ //创建Properties集合对象 Properties po = new Properties(); //使用setProperty往集合中添加数据 po.setProperty("魔神皇","175"); po.setProperty("锁冯金鹏","168"); po.setProperty("烈焰狂狮","160"); //使用stringPropertyNames把Properties集合中的键取出,存储到一个Set集合中 Set<String> set = po.stringPropertyNames(); //使用getProperty方法通过key获取value for (String key : set){ //使用getProperty方法通过key获取value String property = po.getProperty(key); System.out.println(key+"="+property); } } }