先定义一个文件:

实现对文件中资源的访问:
方法一:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Propertiess {
private static Properties ps = new Properties();
static {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.Properties");//用于加载文件
try {
ps.load(in);
} catch (IOException e) {
}
}
public static void main(String[] args) {
String ip = ps.getProperty("ip");
String port = ps.getProperty("port");
System.out.println(ip);
System.out.println(port);
}
方法二:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Propertiess {
private static Properties ps = new Properties();
public static void main(String[] args) throws IOException {
InputStream in = Propertiess.class.getResourceAsStream("test.properties");//加载资源文件
ps.load(in);
String ip = ps.getProperty("ip");//通过getProperty()方法获取值
String port = ps.getProperty("port");
System.out.println(ip);
System.out.println(port)
}
结果:
Java属性文件加载方法
本文介绍了两种使用Java加载属性文件的方法。第一种方法利用Thread.currentThread().getContextClassLoader().getResourceAsStream()来加载位于类路径下的test.Properties文件,并读取其中的ip和port属性值;第二种方法通过直接调用Propertiess类的getResourceAsStream()方法来完成相同任务。
416

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



