第一步:创建一个cofig.properties文件(文件和java文件在同一个包中)
name=\u5173\u7FBD
country=\u8700\u56FD
arm=\u9752\u9F99\u5043\u6708\u5200
第二步:创建java文件
package com.hubin.getproperties;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesTest {
public static void main(String[] args) throws Exception{
//通过文件的相对路径加载配置文件
// InputStream ips=new FileInputStream("src/com/hubin/getproperties/cofig.properties");
//通过类相对路径加载配置文件
InputStream ips=PropertiesTest.class.getResourceAsStream("cofig.properties");
Properties pps=new Properties();
//加载配置文件
pps.load(ips);
//关闭文件流
ips.close();
String ss=pps.getProperty("name");
System.out.println(ss);
}
}
运行结果:
关羽
本文介绍了一个简单的Java程序示例,展示了如何从配置文件(cofig.properties)中读取属性值并打印出来。该程序使用了Properties类来加载属性文件,并通过getResourceAsStream方法定位资源。
2179

被折叠的 条评论
为什么被折叠?



