对于java.util.Properties类,通常我们只需要做到以下3个学习目标:
1、认识properties文件,理解其含义,会正确创建properties文件。
2、会使用java.util.Properties类来操作properties文件。
3、掌握相对路径,能正确书写一个properties文件的相对路径。
而在平时的工作中,会遇到各种各样的需求,以下是一个封装。
欢迎大家关注我的博客!如有疑问,请加QQ群:135430763共同学习!
1、认识properties文件,理解其含义,会正确创建properties文件。
2、会使用java.util.Properties类来操作properties文件。
3、掌握相对路径,能正确书写一个properties文件的相对路径。
而在平时的工作中,会遇到各种各样的需求,以下是一个封装。
package com.herman.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* properties 文件操作工具类
* @author Herman.Xiong
* @date 2015-1-29 下午04:27:19
* @version V3.0
* @since jdk 1.6,tomcat 6.0
*/
public class PropertiesUtil {
private static Properties prop = new Properties();
private static InputStream in;
private static final String path="src/com/herman/config/conf.properties";
/**
* 加载
*/
static{
init();
}
/**
* 初始化
*/
private static void init(){
try {
in=new FileInputStream(new File(path));
prop.load(in);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 关闭InputStream
* @author Herman.Xiong
* @date 2015-1-30 上午09:41:04
*/
private static void close(){
try {
if(null != in)
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 重新加载Properties
* @author Herman.Xiong
* @date 2015-1-30 上午09:41:04
*/
public static void reload(){
close();
prop.clear();//清除所有装载的 键 - 值对
init();
}
/**
* 删除所有键值
* @author Herman.Xiong
* @date 2015-1-30 上午09:42:04
*/
public static void removeAll(){
close();
File file=new File(path);
if(file.exists())
file.delete();
try {
if(!file.exists())
new File(path).createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 输出所有内容到控制台
* @author Herman.Xiong
* @date 2015-1-30 上午09:42:33
*/
public static void outList(){
prop.list(System.out);
}
public static void main(String[] args) {
System.out.println(prop.getProperty("abc"));
outList();
reload();
outList();
removeAll();
System.out.println("重新加载.....");
outList();
}
}
欢迎大家关注我的博客!如有疑问,请加QQ群:135430763共同学习!