读取操作属性配置文件

淩亂°似流年 2022-08-27 11:59 334阅读 0赞

从资源文件里读取值的类,文件后缀不一定要.Properties,只要里面内容如:url=www.cnsec.net
可通过key(url)取得值-www.cnsec.net,简单、强大

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* ReadProperties.java
* Description: 读取操作属性配置文件
* @author li.b
* @version 2.0
* Jun 26, 2008
*/
public class ReadProperties {

  1. /\*\*
  2. \* Description: 获取属性配置文件
  3. \* @param path 资源文件路径
  4. \* @return Properties Object
  5. \* @throws FileNotFoundException
  6. \* @throws IOException
  7. \*/
  8. public static Properties getProperties(String path) throws FileNotFoundException, IOException\{
  9. Properties props = null;
  10. File file = new File(path);
  11. if(file.exists() && file.isFile())\{
  12. props = new Properties();
  13. props.load(new FileInputStream(file));
  14. \}else\{
  15. System.out.println(file.toString() + "不存在!");
  16. \}
  17. return props;
  18. \}
  19. /\*\*
  20. \* Description: 从属性文件获取值
  21. \* @param props Properties Object
  22. \* @param key
  23. \* @return 通过key匹配到的value
  24. \*/
  25. public static String getValue(Properties props,String key,String encod)\{
  26. String result = "";
  27. String en = "";
  28. String localEN = System.getProperty("file.encoding");
  29. if(encod !=null && !encod.equals("") )\{
  30. en = encod;
  31. \}else\{
  32. en = localEN;
  33. \}
  34. try \{
  35. key = new String(key.getBytes(en),"ISO-8859-1");
  36. result = props.getProperty(key);
  37. if(!result.equals(""))\{
  38. result = new String(result.getBytes("ISO-8859-1"),en);
  39. \}
  40. \} catch (Exception e) \{
  41. \}finally\{
  42. if(result == null)result = "";
  43. return result;
  44. \}
  45. \}
  46. public static String getValue(Properties props,String key)\{
  47. return getValue(props, key, "");
  48. \}

}

发表评论

表情:
评论列表 (有 0 条评论,334人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java读取属性配置文件

    文章开始,让我们先了解一下什么是属性配置文件(properties)。 java的通用属性配置文件,以键值对方式存储信息。 还是给个图吧。 ![这里写图片描述][