在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 );