【本文将在CSDN 网 lslyhj 的博客中同步发表 】 转载请注明出处! ! !
http://www.360doc.com/showweb/0/0/387206750.aspx
bleach尸魂界的360图书馆
作者:梨多情
2014 - 06 - 06
附:
1、【.properties 文件】:
文件名:
demo.properties
源码:
name=LSL
age=26
【注意】:
大家在使用的时候,记得修改 .properties 文件的获取路径哦 ! ! !
2、【当前类的 JUnit 单元测试类】:
".properties" 配置文件的3种使用方式(源码) 2.0 -- JUnit 检测
地址:
http://www.360doc.com/showweb/0/0/387208533.aspx
--------------------------------------------- 源码如下 ---------------------------------------------------
package configurationFiles.properties.demo;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author lsl
* .properties 文件 在java 类中的写法
*/
public class PropertiesDemo_JUnit {
/**
* 获取 “.properties” 文件 InputStream 的方式 1。
*/
public InputStream getPropertiesIS_01(){
/*
* 类名.class.getClassLoader().getResourceAsStream(...)方法中的参数为字符串,是文件名,其路径是相对于 src 目录!!!
* 【注意】
* 路径前不要加"/"
*/
InputStream in = PropertiesDemo_JUnit.class.getClassLoader().getResourceAsStream(
"configurationFiles/properties/demo/demo.properties");
return in;
}
/**
* 获取“.properties” 文件 InputStream 的方式 2。
*/
public InputStream getPropertiesIS_02(){
PropertiesDemo_JUnit loadProp = new PropertiesDemo_JUnit();
/*
* 类的引用.getClass().getResourceAsStream(...)方法中的参数为字符串,是文件名,其路径是相对于 src 目录!!!
* 【注意】
* 路径前一定要加"/"
*/
InputStream in = loadProp.getClass().getResourceAsStream(
"/configurationFiles/properties/demo/demo.properties");
return in;
}
/**
* 获取“.properties” 文件 InputStream 的方式 3。
*/
/*
* 不能在 main 方法中测试,可以 new -> Junit 进行单元测试
* 【注意】
* main方法为 static 方法。
* static 方法 -- 只能调用 static 属性及方法。
* this 不能用于 static 方法中。
*/
public InputStream getPropertiesIS_03(){
// PropertiesDemo loadProp = new PropertiesDemo();
/*
* 类的引用.getClass().getResourceAsStream(...)方法中的参数为字符串,是文件名,其路径是相对于 src 目录!!!
* 【注意】
* 1、路径前一定要加"/"
* 2、this -- 表示当前对象,也是“类的引用” !!!!!!
*/
InputStream in = this.getClass().getResourceAsStream(
"/configurationFiles/properties/demo/demo.properties");
return in;
}
//------------------------------------------------------------------------------------------------------------------------//
public void loadPropertiesFile(InputStream is){
try {
InputStream in = is;
Properties p = new Properties();
p.load(in);
System.out.println(p.getProperty("name"));
System.out.println(p.getProperty("age"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。