您的位置:首页 > 编程语言 > Java开发

Java Web 项目中的配置文件路径

2013-01-03 20:45 435 查看
在Java web项目中经常会用属性文件作为配置文件,而其一般放在src的根目录下,读取文件时一般会有以下两种情况:

方式一、在servlet中读取:

Java代码

// action配置文件路径
public static final String ACTIONPATH = "WEB-INF/classes/actions.properties";
// 属性文件
public static final Properties prop = new Properties();
// 获取servlet上下文的绝对路径,如:C:\Program Files\Apache\Tomcat 6.0\webapps\fee\
String path = getServletContext().getRealPath("\\");
// 把文件读入文件输入流,存入内存中
FileInputStream fis = new FileInputStream(new File(path + ACTIONPATH));
//加载文件流的属性
prop.load(fis);


方式二、在一般的类中读取:

Java代码

// action配置文件路径
public static final String ACTIONPATH = "actions.properties";
// 属性文件
public static final Properties prop = new Properties();
// 获取当前类加载的根目录,如:/C:/Program Files/Apache/Tomcat 6.0/webapps/fee/WEB-INF/classes/
String path = UriFilter.class.getClassLoader().getResource("").toURI().getPath();
// 把文件读入文件输入流,存入内存中
FileInputStream fis = new FileInputStream(new File(path + ACTIONPATH));
//加载文件流的属性
prop.load(fis);
读取文件的属性的值:

Java代码

String propertyName = "aa";

String propertyValue = prop.getProperty(propertyName );
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: