eclipse中一般来说有三个地方存放properties配置文件,下面通过一个简单的示例来分别获取配置文件
Demo:
package cn.lxkroom.properties;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;
import org.junit.Test;
public class TestProperties {
//首先读取conf文件夹下的properties文件
@Test
public void testConf() throws Exception{
String path = System.getProperty("user.dir"); //获取项目路径
String filePath=path+"/conf/conf.properties"; //拼串
InputStream is=new FileInputStream(filePath);
Properties prop=new Properties();
prop.load(is);
System.out.println(prop.getProperty("driver"));
}
//读取src以及相同类型的文件夹下的conf.propties文件,最终都在web工程的classes文件中
@Test
public void testSrc() throws Exception{
//通过类加载器,它是JVM内置的一种对象,这些对象负责将硬盘上的字节码加载到内存中
ClassLoader classLoader = TestProperties.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("conf.properties");
//也可以是: /conf/conf.proterties
Properties prop=new Properties();
prop.load(is);
System.out.println(prop.getProperty("user"));
}
//读取任意包下的conf.propties文件
@Test
public void testPackage() throws Exception{
//通过ResourceBundle获取指定包下的配置信息 PS:包里不加后缀名 conf.properties
ResourceBundle bundle = ResourceBundle.getBundle("cn.lxkroom.properties.conf");
String url = bundle.getString("url");
System.out.println(url);
}
}