1.在项目的src目录下,创建.properties文件,本示例以demo.properties为例,在此文件中写入一下代码
id = 001
name = Jack
major = software
2.写一个测试类,TestProperties,如下
package com.properties;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class TestProperties {
private static String basePath = "";// 存储当前项目的路径
private InputStream data = null;
public static void main(String[] args) {
TestProperties tp = new TestProperties();
basePath = tp.getBasePath();
System.out.println("path------>" + basePath);
InputStream in = tp.getResource_1();// 获取资源文件流
tp.showData(in);
tp.closeData();// 关闭数据文件
}
// ------------------获取当前项目的路径
public String getBasePath() {
// ---------方式一
/*
* user.dir是JVM的系统属性,可以通过System.getProperty来获取JVM系统属性
* 所以System.getProperty("user.dir")路径就是文件的默认保存路径
*/
basePath = System.getProperty("user.dir") + "\\src";
// ----------方式二
// basePath = Class.class.getClass().getResource("/").getPath();
return basePath;
}
// -----------------获取数据源------方式一
private InputStream getResource_1() {
// -------通过当前类的字节码文件对象的getResourceAsStream获取
data = TestProperties.class.getResourceAsStream("/demo.properties");
/*
* InputStream in = TestProperties.class.getClassLoader()
* .getSystemResourceAsStream("/demo.properties");
*/
return data;
}
// -----------------获取数据源------方式二
public InputStream getResource_2() {
// --------通过文件获取
try {
data = new FileInputStream(new File(basePath + "/demo.properties"));
} catch (FileNotFoundException e) {
System.out.println("找不到指定文件!");
e.printStackTrace();
}
return data;
}
// --------------------------------显示配置文件内容
public void showData(InputStream in) {
// ------------------------加载配置文件
Properties p = new Properties();
// -----------判断文件是否为空
if (in == null) {
System.out.println("文件没有内容!");
return;// 结束程序
}
try {
p.load(in);
// --------获取配置文件内容
String name = p.getProperty("name");
String id = p.getProperty("id");
String major = p.getProperty("major");
// -----------------输出文件内容
System.out.println("name--------->" + name);
System.out.println("id----------->" + id);
System.out.println("major-------->" + major);
} catch (IOException e) {
System.out.println("加载配置文件出错!");
e.printStackTrace();
}
}
// -------------关闭文件资源
public void closeData() {
try {
data.close();
} catch (IOException e) {
System.out.println("关闭数据文件失败!");
e.printStackTrace();
}
}
}