Java中的Properties类

た 入场券 2023-06-04 06:56 156阅读 0赞

我们可以查看Properties的源码

可以看到,它是继承HashTable的,也就是说它是线程安全的,且里面的数据以键值对存储

  1. class Properties extends Hashtable<Object,Object>

它里面实现了一个方法load(),而load中调用了load0(),可以加载配置文件

  1. private void load0 (LineReader lr) throws IOException {
  2. char[] convtBuf = new char[1024];
  3. int limit;
  4. int keyLen;
  5. int valueStart;
  6. char c;
  7. boolean hasSep;
  8. boolean precedingBackslash;
  9. while ((limit = lr.readLine()) >= 0) {
  10. c = 0;
  11. keyLen = 0;
  12. valueStart = limit;
  13. hasSep = false;
  14. //System.out.println("line=<" + new String(lineBuf, 0, limit) + ">");
  15. precedingBackslash = false;
  16. while (keyLen < limit) {
  17. c = lr.lineBuf[keyLen];
  18. //need check if escaped.
  19. if ((c == '=' || c == ':') && !precedingBackslash) {
  20. valueStart = keyLen + 1;
  21. hasSep = true;
  22. break;
  23. } else if ((c == ' ' || c == '\t' || c == '\f') && !precedingBackslash) {
  24. valueStart = keyLen + 1;
  25. break;
  26. }
  27. if (c == '\\') {
  28. precedingBackslash = !precedingBackslash;
  29. } else {
  30. precedingBackslash = false;
  31. }
  32. keyLen++;
  33. }
  34. while (valueStart < limit) {
  35. c = lr.lineBuf[valueStart];
  36. if (c != ' ' && c != '\t' && c != '\f') {
  37. if (!hasSep && (c == '=' || c == ':')) {
  38. hasSep = true;
  39. } else {
  40. break;
  41. }
  42. }
  43. valueStart++;
  44. }
  45. String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);
  46. String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
  47. put(key, value);
  48. }
  49. }

可以看到,load0会将配置文件以:或者=为中间点,获取key和value,存入

存入之后,我们便可以通过getproperties(“key”)来获取对应的value值

  1. InputStream inputStream=new FileInputStream("C:/Users/86186/Desktop/config.properties");
  2. Properties properties=new Properties();
  3. properties.load(inputStream);
  4. String name=properties.getProperty("name");
  5. System.out.print(name);

发表评论

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

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

相关阅读

    相关 JavaProperties使用

    在项目的开发中,我们经常写一些.properties文件 用来配置一些相关的内容,比如端口号 IP地址 服务器数据库的地址等等 PS 当然这些东西也是能够写在XML 文件内的

    相关 JavaProperties操作

     知识学而不用,就等于没用,到真正用到的时候还得重新再学。最近在看几款开源模拟器的源码,里面涉及到了很多关于Properties类的引用,由于Java已经好久没用了,而这些模拟

    相关 JavaProperties

    一、Java Properties类     Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种