Java配置文件的使用

  1. 创建一个和src同级的目录,名为resources,里面放一个配置文件config.properties:4

内容:
#Crunchify Properties
user=Jerry
company1=Google
company2=eBay
company3=Yahoo

  1. 使用如下的java代码读取这个配置文件:
package partner1;

import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

public class Test {

	public void work(){
		InputStream input = null;
		
		Properties prop = new Properties();
		String propFileName = "config.properties";

		input = getClass().getClassLoader().getResourceAsStream(propFileName);

		if (input != null) {
			try {
				prop.load(input);
				int available = input.available();
				System.out.println("Available: " + available);
				String user = prop.getProperty("user");
				String company1 = prop.getProperty("company1");
				String company2 = prop.getProperty("company2");
				String company3 = prop.getProperty("company3");
	 
				Date time = new Date(System.currentTimeMillis());
				String result = "Company List = " + company1 + ", " + company2 + ", " + company3;
				System.out.println(result + "\nProgram Ran on " + time + " by user=" + user);
				input.close();
			} catch (Exception e) {
				System.out.println("Exception: " + e);
			} finally {
			}
		}
	}
	
	public static void main(String[] args) {
		Test test = new Test();
		test.work();
	}
}

注意resources文件夹需要设置成build path:

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
	<classpathentry excluding="resources/" kind="src" path="src"/>
	<classpathentry kind="src" path="resources"/>

执行结果:

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

展开阅读全文
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值