工作也有一年左右了,发现IO的使用还是很多的,主要是配置文件比较多。虽然理解起来并不复杂,看看源码看看API重新写一个自己需要的也要不了多少时间,权且记下,给自己添加一点印象也给初学者多一点学习资料吧。
要想了解IO,必须知道字符和字节了,具体区别GOOGLE,IO流有分别针对字符和字节的两大分支,这里字符字节分别一个例子。
以property文件为例
1.文件读
文件读取用到InputStream这个抽象类,它是字节输入流的所有类的超类,类很简单没有几个方法,值得一提的是有好几个类扩展了这个类,是学习装饰着模式好例子。
public void read(String resourcePath) throws FileNotFoundException {
InputStream dataStream = new FileInputStream(new File("D:/"
+ resourcePath));
Properties properties = new Properties();
try {
properties.load(dataStream);
dataStream.close();
} catch (IOException e) {
e.printStackTrace();
}
show(properties);
}
public void show(Properties properties) {
Iterator it = properties.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
<noscript></noscript>
上面的Properties 类是资源文件总是使用的类,API上这个解释的:
Properties
类表示了一个持久的属性集。Properties
可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。
一个属性列表可包含另一个属性列表作为它的“默认值”;如果未能在原有的属性列表中搜索到属性键,则搜索第二个属性列表。
以键值对的形式存储数据,此类继承自HashTable.
2.文件写
文件写需要用到OutputStream 这个类,同样它也是个抽象类,和InputStream类一样也被扩展。我喜欢用FileWriter,他们之间的区别是一个是以字符的形式(FileWriter)一个是以字节形式(FileOutputStream)进行处理.
public void write(String resourcePath) {
Properties p = new Properties();
p.setProperty("name", "value");
p.setProperty("name1", "value1");
FileWriter fw;
try {
fw = new FileWriter(new File("src/" + resourcePath), true);
p.store(fw, "auth tmj");
fw.flush();
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
FileWriter构造方法有个boolean类型的参数,这个参数用的比较多,表示是否以追加的方式往文件中写数据。
Properties类中提供了我们在写程序中比较常见的一些方法。
现在比如我要满足一个需求:往资源文件中存数据如果有这个key了就修改key 对应的值,否则插入一个新的。
/**
* 判断是否有相应的key如果有就删除,然后添加
*
* @throws Exception
*/
public void syhNeed() throws Exception {
String fileName = "mysql.property";
InputStream dataStream = new FileInputStream(
new File("src/" + fileName)); // 读取src 目录下的
Properties properties = new Properties();
properties.load(dataStream); // 读取到properties文件中
dataStream.close();
show(properties);
String key = "name2";
String value = "value2";
if (properties.containsKey(key)) {
if (value.equals(properties.get(key))) {
return;
}
properties.remove("name");// 如果有了就删除
}
properties.setProperty(key, value);
FileWriter fw;
fw = new FileWriter(new File("src/" + fileName));// 不能是追加的方式了。
properties.store(fw, null); // 存起来
fw.flush();
fw.close();
}
看看是不是满足要求了,呵呵。
小插曲:
个人比较得瑟,读文件的时候用了
InputStream dataStream = this.getClass().getClassLoader()
.getResourceAsStream(resourcePath);
来得到文件流,OK,src目录下也有这个文件读出来没有问题,但是我用文件修改之后读取出来却没有改变,后面才知道通过这个方式的数据是从内存中读出来的,就算真的修改了,如果内存没有更新取出的数据还是没有改变的。仔细看了也难怪,这个得到的classLoader肯定是内存的东东呀。然后得到classLoader中的资源必须也是内存中的啊。
<noscript></noscript>