io的异常处理以及properties
- try(流对象的创建) { 对象的处理逻辑} catch(IOException e) { 异常的处理逻辑}
public static void test4(){try(FileWriter fw=new FileWriter("a.txt",true); ){char[] cbuf={'a'};//写入一个字符串组fw.write(cbuf);}catch(IOException e){e.printStackTrace();}}
- 上面的流对象可以多个,并且最后不必调用close,会在执行完毕之后自动close
Properties是一个双列集合,key和value默认都是字符串
常见方法:
Object setProperty(String key ,String value) 调用Hashtable的方法put
String getProperty(String key)通过key来获取对应的value
Set stringPropertyNames()返回列表的键的集合
public static void test5() {Properties pro=new Properties();pro.setProperty("zs","19");pro.setProperty("ls","18");pro.setProperty("ww","17");Set<String> keys=pro.stringPropertyNames();for (String key : keys) {System.out.println(pro.getProperty(key));}}
- 保存流对象的使用步骤
创建properties集合对象,添加数据
创建字符或者字节输出流对象,绑定输出文件
使用properties对象的store方法,把集合中的临时数据持久化的保存到硬盘中保存
public static void test6() throws IOException {Properties pro=new Properties();pro.setProperty("zs","19");pro.setProperty("ls","18");pro.setProperty("ww","17");FileWriter fw=new FileWriter("pro.txt");pro.store(fw,"集合");fw.close();}
- 从文件中拂去流对象的步骤
创建properties对象
创建字符或者字节输出流对象FileReader,绑定输出文件
使用properties对象的load方法传入FileReader对象
利用properties对象的stringPropertyNames方法获取所有键
利用properties对象的getProperty获取值
public static void test7() throws IOException {FileReader fr=new FileReader("pro.txt");Properties pr=new Properties();pr.load(fr);Set<String> keys=pr.stringPropertyNames();for (String key : keys) {System.out.println(pr.getProperty(key));}fr.close();}