加载.properties文件的几种方式

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();
		}
	}
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值