PropertiesIoUtiles工具类
public class PropertiesIoUtiles {
/**
* 从文件中读取出数据
* @param k key值
* @return 读取到的数据
*/
public static String readFile(String k,String path){
File directory = new File("");//参数为空
String courseFile = null;
try {
//这里是需要读取数据的配置文件的路径,可根据实际路径设定
String webPath = TheApp.getWebDiskPath();
courseFile = webPath + "WEB-INF\\" + path;
File file = new File(courseFile);
if(!file.exists()){
return "";
}
Properties prop = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(courseFile));
prop.load(in);
Iterator<String> iterator = prop.stringPropertyNames().iterator();
while (iterator.hasNext()){
String key = iterator.next();
if(key.equals(k)){
return prop.getProperty(key);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* 把数据存到文件中
* @param map 存入数据的map
*/
public static boolean writeFile(Map<String,String> map,String path){
File directory = new File("");//参数为空
String courseFile = null;
try {
//这里是需要存储数据的配置文件的路径,可根据实际路径设定
String webPath = TheApp.getWebDiskPath();
courseFile = webPath + "WEB-INF\\" + path;
File file = new File(courseFile);
if(!file.exists()){
file.createNewFile();
}
Properties prop = new Properties();
FileOutputStream out = new FileOutputStream(courseFile, false);
for(String mapkey : map.keySet()){
String value = map.get(mapkey);
prop.setProperty(mapkey,value);
prop.store(out, mapkey);
}
out.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
还有另外一种方式获取配置文件的变量:
InputStream is = LoginController.class.getClassLoader().getResourceAsStream("app.properties");
Properties p = new Properties();
try {
p.load(is);
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
String code = p.getProperty("parent.branch.code");
System.out.println(code);
注意:LoginController是某个类名,可根据具体实体类作修改