Java 中的 Properties 类函数

首页 / Java入门教程 / Java 中的 Properties 类函数

Properties是Hashtable的子类。它用于维护值列表,其中键是字符串,并且值也是字符串。

属性(Properties)定义以下变量。此变量保存与Properties对象关联的默认属性列表。

Properties defaults;

以下是properties类提供的构造函数的列表。

Sr.No.Constructor & Remark
1

Properties()

此构造函数创建一个没有默认值的Properties对象。

2

Properties(Properties propDefault)

创建一个使用propDefault作为其默认值的对象。

除了Hashtable定义的方法外,Properties还定义了以下方法-

Sr.No.Method & Remark
1

String getProperty(String key)

返回与键关联的值。

2

String getProperty(String key,String defaultProperty)

返回与键关联的值;

3

void list(PrintStream streamOut)

将属性列表发送到链接到streamOut的输出流。

4

vlid list(PrintWriter streamOut)

无涯教程网

将属性列表发送到链接到streamOut的输出流。

5

void load(InputStream streamIn) throws IOException

从链接到streamIng的输入流中输入属性列表。

6

Enumeration propertyNames()

返回键的枚举。

7

Object setProperty(String key,String value)

将价值与键相关联。

8

void store(OutputStream streamOut, String description)

写入由description指定的字符串后,将属性列表写入链接到streamOut的输出流。

Properties 示例

以下程序说明了此数据结构支持的几种方法-

import java.util.*;
public class PropDemo {

   public static void main(String args[]) {
      Properties capitals=new Properties();
      Set states;
      String str;
      
      capitals.put("Illinois", "Springfield");
      capitals.put("Missouri", "Jefferson City");
      capitals.put("Washington", "Olympia");
      capitals.put("California", "Sacramento");
      capitals.put("Indiana", "Indianapolis");

      //在哈希表中显示所有州和首都。
      states=capitals.keySet();   //获取键的集合视图
      Iterator itr=states.iterator();
      
      while(itr.hasNext()) {
         str=(String) itr.next();
         System.out.println("The capital of " + str + " is " + 
            capitals.getProperty(str) + ".");
      }     
      System.out.println();

      //查找不在列表中的状态——指定默认值
      str=capitals.getProperty("Florida", "Not Found");
      System.out.println("The capital of Florida is " + str + ".");
   }
}

这将产生以下输出-

The capital of Missouri is Jefferson City.
The capital of Illinois is Springfield.
The capital of Indiana is Indianapolis.
The capital of California is Sacramento.
The capital of Washington is Olympia.

The capital of Florida is Not Found.

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入拆解Java虚拟机 -〔郑雨迪〕

从0开始学微服务 -〔胡忠想〕

深入剖析Kubernetes -〔张磊〕

分布式协议与算法实战 -〔韩健〕

职场求生攻略 -〔臧萌〕

OAuth 2.0实战课 -〔王新栋〕

大厂晋升指南 -〔李运华〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

手把手教你落地DDD -〔钟敬〕

好记忆不如烂笔头。留下您的足迹吧 :)