java中Properties文件加载和使用方法

2025-05-29 0 63

一.properties简介

properties 类继承自hashtable,提供的方法很像map的实现类hashmap。它在 java 编程的早期就有了,并且几乎没有什么变化。j2se 的 tiger 版本增强了这个类,不仅可以用它在单独一行中指定用等号分隔的多个键-值对(其中键和值是用等号分隔的),还可以用xml 文件装载和保存这些键-值对。

二.properties加载和简单的使用

1.路径存放

java中Properties文件加载和使用方法

2.信息配置

?

1

2
name = lily

age = 22

3.简单的加载和使用

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34
package com.my.utils;

import java.io.ioexception;

import java.io.inputstream;

import java.util.properties;

public class loadprop {

public static void main(string[] args) {

// todo auto-generated method stub

properties prop = new properties();

inputstream in = loadprop.class.getclassloader().getresourceasstream("config/prop.properties");

try {

prop.load(in);

system.out.println(prop.get("name"));

prop.setproperty("name", "lucy");

system.out.println(prop.get("name"));

} catch (ioexception e) {

// todo auto-generated catch block

e.printstacktrace();

}finally {

try {

in.close();

} catch (ioexception e) {

// todo auto-generated catch block

e.printstacktrace();

}

}

}

}

4.使用 java.util.enumeration 获取所有key

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39
package com.my.utils;

import java.io.ioexception;

import java.io.inputstream;

import java.util.enumeration;

import java.util.properties;

public class loadprop {

@suppresswarnings("unchecked")

public static void main(string[] args) {

// todo auto-generated method stub

properties prop = new properties();

inputstream in = loadprop.class.getclassloader().getresourceasstream("config/prop.properties");

enumeration<string> en = null;

string key = null;

try {

prop.load(in);

en = (enumeration<string>) prop.propertynames();

while (en.hasmoreelements()) {

key = (string) en.nextelement();

system.out.println(key);

}

} catch (ioexception e) {

// todo auto-generated catch block

e.printstacktrace();

}finally {

try {

in.close();

} catch (ioexception e) {

// todo auto-generated catch block

e.printstacktrace();

}

}

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://www.cnblogs.com/lukelook/p/8660418.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java中Properties文件加载和使用方法 https://www.kuaiidc.com/112358.html

相关文章

发表评论
暂无评论