项目的目录结构
使用getResourceAsStream方法和InputStream流去读取properties文件,使用getResourceAsStream方法去读取properties文件时需要特别注意properties文件路径的写法,
public class PropertiesFileReadTest {
/**
* 使用getResourceAsStream方法读取properties文件
*/
static void readPropFileByGetResourceAsStream() {
/**
* 读取src下面config.properties包内的配置文件
* test1.properties位于config.properties包内
*/
InputStream in1 = PropertiesFileReadTest.class.getClassLoader()
.getResourceAsStream("config/properties/test1.properties");
/**
* 读取和PropertiesFileReadTest类位于同一个包里面的配置文件
* test2.properties和PropertiesFileReadTest类在同一个包里面
*/
InputStream in2 = PropertiesFileReadTest.class
.getResourceAsStream("test2.properties");
/**
* 读取src根目录下文件的配置文件
* jdbc.properties位于src目录
*/
InputStream in3 = PropertiesFileReadTest.class.getClassLoader()
.getResourceAsStream("jdbc.properties");
/**
* 读取位于另一个source文件夹里面的配置文件
* config是一个source文件夹,config.properties位于config source文件夹中
*/
InputStream in4 = PropertiesFileReadTest.class.getClassLoader()
.getResourceAsStream("config.properties");
Properties p = new Properties();
p.load(in1);
System.out.println("test1.properties:name=" + p.getProperty("name")
+ ",age=" + p.getProperty("age"));
其他略....
}
/**
* 使用InPutStream流读取properties文件
*/
static void readPropFileByInPutStream() {
/**
* 读取src根目录下文件的配置文件
* jdbc.properties位于src目录
*/
InputStream in1 = new BufferedInputStream(new FileInputStream(
"src/jdbc.properties"));
/**
* 读取src下面config.properties包内的配置文件
* test1.properties位于config.properties包内
*/
InputStream in2 = new BufferedInputStream(new FileInputStream(
"src/config/properties/test1.properties"));
/**
* 读取和PropertiesFileReadTest类位于同一个包里面的配置文件
* test2.properties和PropertiesFileReadTest类在同一个包里面
*/
InputStream in3 = new BufferedInputStream(new FileInputStream(
"src/propertiesFile/read/test/test2.properties"));
/**
* 读取位于另一个source文件夹里面的配置文件
* config是一个source文件夹,config.properties位于config source文件夹中
*/
InputStream in4 = new FileInputStream("config/config.properties");
Properties p = new Properties();
p.load(in1);
其他略....
}
}
以上参考自博客:http://www.cnblogs.com/xdp-gacl/p/3640211.html
ClassPath : 指的是:WEB-INF\classes这个目录下,通常把文件放在src文件夹下,或者新建文件并且添加到build path即可。IDE在同步文件到tomcat时会自动将文件放在classes下。 InputStream in = this.getClass().getResourceAsStream("路径名"); //一般为“/”相对classpath的路径,这样就不需要读取绝对路径了 在java web项目中添加配置文件,满足数据库配置参数以及其他自定义参数存放, 可自己写一个配置文件**.properties,把项目所需的自定义配置信息以名值对的形式写入文件。把它放到项目的源文件包src下,部署时IDE会自动将其复制到相应路径。 java web项目未开启服务(有没有部署到tomcat中一样)使用this.getClass().getResource("/")得到Url对象,打印如下: file:/F:/zgh/myworkspace/collection/WebRoot/WEB-INF/classes/ 此路径为java web项目源路径。 部署到tomcat中的java web项目开启服务后使用this.getClass().getResource("/")得到Url对象,打印如下: file:/F:/zgh/software/apache-tomcat-6.0.14/webapps/collection/WEB-INF/classes/ java application项目使用this.getClass().getResource("/")得到Url对象,打印如下: file:/F:/zgh/myworkspace/javaeye/bin/ 此路径为java application项目的class文件的根路径。 注意:未开启tomcat web服务时打印的不是上面的路径,是你的项目源文件的classes路径。