项目中常常会有一些配置,除了将其写在一个常量类中外,写在配置文件中也是一种不错的选择,下面先介绍下,如何使用properties文件
java中有一个 Properties类,该类有一个方法,从一个流中加载文件
/**
* Loads properties from the specified {@code InputStream}, assumed to be ISO-8859-1.
* See "<a href="#character_encoding">Character Encoding</a>".
*
* @param in the {@code InputStream}
* @throws IOException
*/
public synchronized void load(InputStream in) throws IOException {
if (in == null) {
throw new NullPointerException("in == null");
}
load(new InputStreamReader(in, "ISO-8859-1"));
}
可以通过下面的工具类来获取一个properties对象:
public class Utils {
/**
* 得到config.properties配置文件中的所有配置属性
*
* @return Properties对象
*/
public static Properties getNetConfigProperties() {
Properties props = new Properties();
InputStream in = Utils.class.getResourceAsStream("/config.properties");
try {
props.load(in);
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
}
下面演示单元测试的配置:
在AndroidManifest.xml中配置如下:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
.....
<!-- 加入单元测试 -->
<uses-library android:name="android.test.runner" />
</application>
<!-- 代表把单元测试框架中的一些依赖库引入进来 -->
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:label="Test for my app"
android:targetPackage="com.example.testpropertyfile"/>
这里targetPackage是你的应用包名
事例包结构如下:
public class TestPropUtilsTest extends AndroidTestCase{
public void testPropUtils(){
Properties properties = Utils.getNetConfigProperties();
System.out.println(properties.getProperty("IP"));
Log.i("szm--", properties.getProperty("IP"));
}
}