在Java web项目中经常会用属性文件作为配置文件,而其一般放在src的根目录下,读取文件时一般会有以下两种情况:
方式一、在servlet中读取:
Java代码
方式二、在一般的类中读取: Java代码
Java代码
String propertyName = "aa";
String propertyValue = prop.getProperty(propertyName );
方式一、在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 );
本文介绍在JavaWeb项目中如何从src根目录读取属性文件作为配置文件,并提供两种常见读取方式的具体实现,包括在servlet及普通类中的应用。
236

被折叠的 条评论
为什么被折叠?



