方式一:采用ServletContext读取,读取配置文件的realpath,然后通过文件流读取出来。
因为是用ServletContext读取文件路径,所以配置文件可以放入在web-info的classes目录中,也可以在应用层级及web-info的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在web-info及webroot下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。缺点:不能在servlet外面应用读取配置信息。
public class ReadPage extends HttpServlet {
private static final String DRIVER = "jdbc.driverClassName";
private static final String URL = "jdbc.url";
private static final String ROOT = "jdbc.username";
private static final String PASS = "jdbc.password";
/**
* Constructor of the object.
*/
public ReadPage() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* 读取web-info的配置文件 方法覆盖
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 配置文件的跟路径
String path = "/WEB-INF/jdbc.properties";
// 获取服气端的相对路径//localhost:8080/web
String realPath = getServletContext().getRealPath(path);
Properties properties = new Properties();
File file = new File(realPath);
FileInputStream inStream = new FileInputStream(file);
properties.load(inStream);
System.out.println(properties.get(DRIVER));
System.out.println(properties.get(URL));
System.out.println(properties.get(ROOT));
System.out.println(properties.get(PASS));
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
方式二:采用ResourceBundle类读取配置信息,
优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。
缺点:只能加载类classes下面的资源文件且只能读取.properties文件。
import java.io.File;
import java.io.ObjectInputStream.GetField;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
Properties properties =getProperties("jdbc.properties",Locale.ENGLISH);
Set<Entry<Object, Object>> entrySet = properties.entrySet();
Iterator<Entry<Object, Object>> iterator = entrySet.iterator();
while(iterator.hasNext()){
Entry<Object, Object> next = iterator.next();
System.out.println(next.getKey());
System.out.println(next.getValue());
}
}
public static Properties getProperties( String fileString ,Locale a){
ResourceBundle resourceBundle=ResourceBundle.getBundle(fileString,a);
Properties properties=new Properties();
Enumeration<String> keys = resourceBundle.getKeys();
while(keys.hasMoreElements()){
String key=keys.nextElement();
String value=resourceBundle.getString(key);
properties.setProperty(key, value);
}
return properties;
}
}
方式三:采用ClassLoader方式进行读取配置信息
优点是:可以在非Web应用中读取配置资源信息,
可以读取任意的资源文件信息
缺点:只能加载类classes下面的资源文件。
/**
* 通过classLoader类来加载数据
*
* @Title: ClassLoader.java
* @Package vc.xiao.art
* @Description: TODO
* @author Administrator
* @date 2017年1月17日 下午4:03:29
* @version V1.0
*/
public class ClassLoader {
public static void main(String[] args) throws IOException {
String fileName = "jdbc.properties";
Properties properties = readFile(fileName);
Set<Entry<Object, Object>> entrySet = properties.entrySet();
Iterator<Entry<Object, Object>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<Object, Object> next = iterator.next();
System.out.println(next.getKey() + "=" + next.getValue());
}
}
public static Properties readFile(String filename) throws IOException {
InputStream inputstream = ClassLoader.class.getClassLoader()
.getResourceAsStream(filename);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputstream));
Properties properties = new Properties();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
String st[] = str.split("=");
properties.setProperty(st[0], st[1]);
}
return properties;
}
}
方式四 PropertiesUtil读取配置文件
public class PropertiesLoader {
public static void main(String[] args) throws IOException {
Properties properties = getPro();
Set<Entry<Object, Object>> entrySet = properties.entrySet();
Iterator<Entry<Object, Object>> it = entrySet.iterator();
while (it.hasNext()) {
Entry<Object, Object> next = it.next();
System.out.println(next.getKey() + ":" + next.getValue());
}
}
public static Properties getPro() throws IOException {
Properties properties = null;
properties = PropertiesLoaderUtils.loadAllProperties("jdbc.properties");
return properties;
}
}
方式五 修改properties文件
public class ChangeProperties {
private static Map<String, String> map = new HashMap<String, String>();
// 初始化的时候先把数据放到map集合中
public ChangeProperties() {
map.put("jdbc.driverClassName", "com.mysql.jdbc.Driver");
map.put("jdbc.url", "jdbc:mysql://localhost:3306/spring");
map.put("jdbc.username", "root");
map.put("jdbc.password", "bjsxt");
map.put("aaa", "bbbb");
}
public static void main(String[] args) throws IOException {
ChangeProperties changeProperties=new ChangeProperties();
writeProperties("jdbc.properties");
}
public static void writeProperties(String file) throws IOException {
// 先获取到配置文件
String Filepath = ChangeProperties.class.getClassLoader()
.getResource(file).getFile();
Properties properties = PropertiesLoaderUtils
.loadAllProperties(Filepath);
// 清空配置文件
properties.clear();
Set<Entry<String, String>> set=map.entrySet();
Iterator<Entry<String, String>> it=set.iterator();
while(it.hasNext()){
Entry<String, String> next =it.next();
properties.setProperty(next.getKey(), next.getValue());
}
// 准备以字节流的方式输出到配置文件
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(new File(Filepath))));
System.out.println(properties);
properties.store(writer, "");
System.out.println(properties);
writer.flush();
writer.close();
}
}