java 4种方式读取配置文件 + 修改配置文件

方式一:采用ServletContext读取,读取配置文件的realpath,然后通过文件流读取出来。

因为是用ServletContext读取文件路径,所以配置文件可以放入在web-infoclasses目录中,也可以在应用层级及web-info的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在web-infowebroot下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xmlproperties。缺点:不能在servlet外面应用读取配置信息。

具体举例如下:

[html]  view plain  copy
  1. //ServletContext.getRealPath(name)读取路径  
  2.     privatevoid test1(HttpServletRequest request, HttpServletResponseresponse)  
  3.     throwsServletException,IOException {  
  4.        //response.setContentType("text/html;charset=utf-8");  
  5.        String path = "/WEB-INF/jdbc_connection.properties"; //读取WEB-INF中的配置文件  
  6.        String realPath = getServletContext().getRealPath(path);//getServletContext()相当于http://localhost/demo05  
  7. //所以后面的path只需要以应用demo/开头具体的部署目录路径即可,如上面的/web-in…  
  8.        System.out.println(realPath);  
  9.        InputStreamReader reader =new InputStreamReader(newFileInputStream(realPath),"utf-8");  
  10.        Properties props = new Properties();  
  11.        props.load(reader); //load个人建议还是用Reader来读,因为reader体系中有个InputStreamReader可以指定编码  
  12.        String jdbcConValue = props.getProperty("jdbc_con");  
  13.        System.out.println(jdbcConValue);  
  14.        System.out.println("加载src包下的资源------------------------");  
  15.        path = "/WEB-INF/classes/com/test/servlet/jdbc_connection.properties"; //读取WEB-INF中的配置文件  
  16.         realPath=getServletContext().getRealPath(path);  
  17.        System.out.println(realPath);  
  18.        reader = new InputStreamReader(new FileInputStream(realPath),"utf-8");  
  19.        props.load(reader); //load个人建议还是用Reader来读,因为reader体系中有个InputStreamReader可以指定编码  
  20.        jdbcConValue = props.getProperty("jdbc_con");  
  21.        System.out.println("second::"+jdbcConValue);  
  22.         
  23.     }  


方式二:采用ResourceBundle类读取配置信息,

优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。

缺点:只能加载类classes下面的资源文件且只能读取.properties文件。

[html]  view plain  copy
  1. /**  
  2.      * 获取指定配置文件中所以的数据  
  3.      * @param propertyName  
  4.      *        调用方式:  
  5.      *            1.配置文件放在resource源包下,不用加后缀  
  6.      *              PropertiesUtil.getAllMessage("message");  
  7.      *            2.放在包里面的  
  8.      *              PropertiesUtil.getAllMessage("com.test.message");  
  9.      * @return  
  10.      */  
  11.     public static List<String> getAllMessage(String propertyName) {  
  12.         // 获得资源包  
  13.         ResourceBundle rb = ResourceBundle.getBundle(propertyName.trim());  
  14.         // 通过资源包拿到所有的key  
  15.         Enumeration<String> allKey = rb.getKeys();  
  16.         // 遍历key 得到 value  
  17.         List<String> valList = new ArrayList<String>();  
  18.         while (allKey.hasMoreElements()) {  
  19.             String key = allKey.nextElement();  
  20.             String value = (String) rb.getString(key);  
  21.             valList.add(value);  
  22.         }  
  23.         return valList;  
  24.     }  

方式三:采用ClassLoader方式进行读取配置信息

优点是:可以在非Web应用中读取配置资源信息, 可以读取任意的资源文件信息
 缺点:只能加载类classes下面的资源文件。
[html]  view plain  copy
  1. /**获取的是class的根路径下的文件  
  2.      * 优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息  
  3.      * 缺点:只能加载类classes下面的资源文件。  
  4.      * 如果要加上路径的话:com/test/servlet/jdbc_connection.properties  
  5.      */  
  6.     private static void use_classLoador(){  
  7.         //文件在class的根路径  
  8.         InputStream is=TestJava.class.getClassLoader().getResourceAsStream("message.properties");  
  9.         //获取文件的位置  
  10.         String filePath=TestJava.class.getClassLoader().getResource("message.properties").getFile();  
  11.         System.out.println(filePath);  
  12.         //获取的是TestJava类所在的相对路径下 ,com/test/servlet/jdbc_connection.properties"  
  13. //      InputStream is2=TestJava.class.getResourceAsStream("message.propertie");  
  14.           
  15.         BufferedReader brnew BufferedReader(new InputStreamReader(is));  
  16.         Properties props = new Properties();  
  17.           
  18.         try {  
  19.             props.load(br);  
  20.             for (Object s : props.keySet())   
  21.                 System.out.println(s);  
  22.         } catch (IOException e) {   e.printStackTrace();}  
  23.     }  

方法4 getResouceAsStream

XmlParserHandler.class.getResourceAsStream 与classloader不同
使用的是当前类的相对路径
[html]  view plain  copy
  1. BufferedReader br=new BufferedReader(      
  2.         new InputStreamReader(XmlParserHandler.class.      
  3.                 getResourceAsStream("./rain.xml"), "GB2312"));// ./代表当前目录不写也可以      
  4. InputSource is=new InputSource(br);//数据源   

方法5 PropertiesLoaderUtils工具类


[html]  view plain  copy
  1. /**  
  2.      * Spring 提供的 PropertiesLoaderUtils 允许您直接通过基于类路径的文件地址加载属性资源  
  3.      * 最大的好处就是:实时加载配置文件,修改后立即生效,不必重启  
  4.      */  
  5.     private static void springUtil(){  
  6.         Properties props = new Properties();  
  7.         while(true){  
  8.             try {  
  9.                 props=PropertiesLoaderUtils.loadAllProperties("message.properties");  
  10.                 for(Object key:props.keySet()){  
  11.                     System.out.print(key+":");  
  12.                     System.out.println(props.get(key));  
  13.                 }  
  14.             } catch (IOException e) {  
  15.                 System.out.println(e.getMessage());  
  16.             }  
  17.               
  18.             try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}  
  19.         }  
  20.     }  

修改Properties

[html]  view plain  copy
  1. /**  
  2.      * 传递键值对的Map,更新properties文件  
  3.      *   
  4.      * @param fileName  
  5.      *            文件名(放在resource源包目录下),需要后缀  
  6.      * @param keyValueMap  
  7.      *            键值对Map  
  8.      */  
  9.     public static void updateProperties(String fileName,Map<String, String> keyValueMap) {  
  10.         // InputStream  
  11.         // inputStream=PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);//输入流  
  12.         String filePath = PropertiesUtil.class.getClassLoader()  
  13.                 .getResource(fileName).getFile();// 文件的路径  
  14.         System.out.println("propertiesPath:" + filePath);  
  15.         Properties props = new Properties();  
  16.         BufferedReader br = null;  
  17.         BufferedWriter bw = null;  
  18.   
  19.         try {  
  20.             // 从输入流中读取属性列表(键和元素对)  
  21.             br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));  
  22.             props.load(br);  
  23.             br.close();  
  24.   
  25.             // 写入属性文件  
  26.             bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));  
  27.             props.clear();// 清空旧的文件  
  28.             for (String key : keyValueMap.keySet())  
  29.                 props.setProperty(key, keyValueMap.get(key));  
  30.             props.store(bw, "");  
  31.             bw.close();  
  32.         } catch (IOException e) {  
  33.             System.err.println("Visit " + filePath + " for updating " + ""+ " value error");  
  34.         } finally {  
  35.             try {  
  36.                 br.close();  
  37.                 bw.close();  
  38.             } catch (IOException e) {  
  39.                 e.printStackTrace();  
  40.             }  
  41.         }  
  42.     }  

猜你喜欢

转载自blog.csdn.net/qq_36544760/article/details/79962320