加载.properties文件的几种方式

来源:互联网 发布:windows arp欺骗工具 编辑:程序博客网 时间:2024/05/19 19:14

1.在项目的src目录下,创建.properties文件,本示例以demo.properties为例,在此文件中写入一下代码

id = 001name = Jackmajor = 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();}}}