资源文件解析


作用:解析配置文件并解决硬编码(在代码中写死的部分)

作者:Z-AI

以下代码是通过Junit4运行的,如果没有添加Junit4 jar包会报错

推荐使用:方式一:线程方式获取类加载器

/**
	 * 使用当前线程的类加载器
	 * @throws IOException 
	 */
	@Test
	public void testThread() throws IOException {
		//当前线程的类加载器
		ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
		InputStream resourceAsStream = contextClassLoader.getResourceAsStream("db.properties");
		Properties prop = new Properties();
		prop.load(resourceAsStream);
		String username = prop.getProperty("username");
		String password = prop.getProperty("password");
		System.out.println(username);
		System.out.println(password);
	}

方式二:传统IO流读取

/***
	 * 传统IO方式读取配置文件
	 * 这种方式存在硬编码问题,new FileInputStream("C:\\Users\\maple\\Desktop\\itsourcejava\\EE_WorkSpace\\Day27\\src\\db.properties");
	 * @throws IOException 
	 */
	@Test
	public void testIO() throws IOException {
		InputStream fis = new FileInputStream("db.properties的路径");
		Properties prop = new Properties();
		prop.load(fis);
		String username = prop.getProperty("username");
		String password = prop.getProperty("password");
		System.out.println(username);
		System.out.println(password);
	}

方式三:使用字节码对象读取配置文件

/**
	 * 使用字节码对象读取配置文件
	 * 此方式也不好,需要指定字节码对象ThreadProperties.class.getResourceAsStream("/db.properties");
	 * @throws IOException 
	 */
	@Test
	public void testClass() throws IOException {
		//使用的是相对路径
		InputStream resourceAsStream = ThreadProperties.class.getResourceAsStream("/db.properties");
		Properties prop = new Properties();
		prop.load(resourceAsStream);
		String username = prop.getProperty("username");
		String password = prop.getProperty("password");
		System.out.println(username);
		System.out.println(password);
	}

方式四:使用类加载器读取配置文件

/**
	 * 使用类加载器读取配置文件
	 * 此方式也不好,需要指定字节码对象ThreadProperties.class.getClassLoader().getResourceAsStream("db.properties");
	 * @throws IOException 
	 */
	@Test
	public void testClassLoader() throws IOException {
		InputStream resourceAsStream = ThreadProperties.class.getClassLoader().getResourceAsStream("db.properties");
		Properties prop = new Properties();
		prop.load(resourceAsStream);
		String username = prop.getProperty("username");
		String password = prop.getProperty("password");
		System.out.println(username);
		System.out.println(password);
	}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值