在项目中properties文件的读取是必不可少的,在这里写一个简单的例子
package filemanage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class PropertiesExample {
public static void main(String[] args) {
getPropertiesByKey("test.properties","username2");
}
/**
* 根据文件名和相应的key读取properties文件内容
* @param fileName
* @param key
* @return
*/
public static String getPropertiesByKey(String fileName,String key){
String result = "";
Map map=new HashMap();
//test.properties放在src根目录下
URL url = PropertiesExample.class.getClassLoader().getResource(fileName);
//如果文件不存在就返回null
if(url == null){
System.out.println("文件不存在");
return "文件不存在";
}
Properties p = new Properties();
InputStream in = null;
try {
//直接通过getResourceAsStream得到文件流也可以使用new FileInputStream(new File("文件路径"))
in = PropertiesExample.class.getClassLoader().getResourceAsStream(fileName);;
p.load(in);
result = p.get(key).toString();
/**************************读取properties文件中所有key和value并且把所有值都放在map中******************************************************************/
//获得properties中所有的键放于枚举类型中!
Enumeration enu=p.keys();
while(enu.hasMoreElements()){
//获得一个keyStr
String keyStr=enu.nextElement().toString();
//获得 该key 对应的 value
String value=p.getProperty(keyStr);
System.out.println(keyStr+" "+value);
//将 key 和 value 以utf-8的方式进行编码转换 ,经过测试,没有进行编码转换的是ok,所有需不需要进行转换得根据实际情况来看
try {
keyStr = new String(key.getBytes("ISO8859-1"),"UTF-8");
value = new String(value.getBytes("ISO8859-1"),"UTF-8");
System.out.println(keyStr+" "+value);
//放入map
map.put(key,value);
}
catch (UnsupportedEncodingException e) {
System.out.println("编码失败!");
}
}
/********************************************************************************************/
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally{
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}