读取Properties配置文件

一,Android中

  在Android中读取配置文件,可以使用System.getProperties()方法读取:

    1,在res资源目录下,新建一个文件夹 raw,然后在其下创建一个.properties文件.如:

request_char=utf-8
URL=http://192.168.1.101:8080/ServerAQI/JsonAction
range_long=7
#days
from_date_name=fromDate
to_date_name=toDate

    2,可以定义一个工具类,接受android.content.res.Resources类型的参数,返回Properties对象,如:

package spt.assist;

import java.io.IOException;
import java.util.Properties; import android.content.res.Resources.NotFoundException;
import android.util.Log; import spt.aqi.activity.R; public class PropertyConfig {
/**获取配置文件信息中的指定值.
* @param resources
* @param key
* @return
*/
public static String getProperty(android.content.res.Resources resources,
String key) {
Properties properties = getProperties(resources);
return properties.getProperty(key);
} /**获取配置文件中的信息.
* @param resources
* @return
*/
public static Properties getProperties(
android.content.res.Resources resources) {
Properties props = new Properties();
try {
props.load(resources.openRawResource(R.raw.properties));
} catch (NotFoundException e) {
Log.i("sysout",
"ResourceSearcher:OpenFileFromUtil:" + e.getMessage());
e.printStackTrace();
return null;
} catch (IOException e) {
Log.i("sysout",
"ResourceSearcher:OpenFileFromUtil:" + e.getMessage());
e.printStackTrace();
return null;
}
return props;
}
}

    3,在Android中的资源类ContextWrapper的子类(如Activity或Service)类中调用调用getResources()方法并传入上面的工具类的方法,如,在Service类中,

final String url = PropertyConfig.getProperty(getResources(), "URL");

二,普通的java中

  在Android中特有的使用android.content.res.Resources的方式有点局限性,就是必须在ContextWrapper的子类中获取android.content.res.Resources,所以以上可以使用URL来解决:

  1)将raw/properties.properties放在src目录下,然后调用

URL url = PropertyConfig.class.getClassLoader().getResource("raw/properties.properties");

获取URL,然后可以调用该类的url.openStream()获取InputStream,然后后面的内容一样.

三,java web中

  1,在Servlet中,可以使用javax.servlet.GenericServlet的ServletContext()方法读取,如:

String path = "/WEB-INF/jdbc_connection.properties"; //读取WEB-INF中的配置文件

       String realPath = getServletContext().getRealPath(path);//getServletContext()相当于http://localhost/demo05

  2,在普通的自定义的类中,可以使用ClassLoader读取,如:

		// 获取配置文件
String filePath;
File file = null;
try {
filePath = PropertyConfig.class.getClassLoader().getResource("").toURI().getPath(); // web-inf/classes
filePath = filePath.substring(1); // 去掉最前面的/符号.
file = new File(filePath).getParentFile(); // 发现运行后,该目录下文件会被替换,所有不建议放在classes目录下,况且,本不应数据class文件.
file = new File(file + "/raw/conf.properties");

此时raw/properties.properties配置文件放置在Web-inf/classes下,如:WebRoot\WEB-INF\raw\properties.properties.值得注意的是,我运行过程序,发现如果将配置文件直接放在Web-inf/classes下,响应中断后,会被替换,所以不要将配置文件直接放在该目录下,况且,本来配置文件就不属于class文件,理当然不该直接放在Web-inf/classes目录下.

上一篇:RPM


下一篇:Qt 5.9.4 如何静态编译和部署?