JAVA配置文件取值方法

来源:互联网 发布:虎门巨新网络跑路后续 编辑:程序博客网 时间:2024/06/15 09:54

其实是很简单基础的东西,但对于初学者来说多掌握点东西总是好的,多的不说,直接上代码了,最简单粗暴的方式。

一、XML配置文件:

1.GlobalConfig.xml配置文件

<?xml version="1.0" encoding="UTF-8"?><Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">    <db_ip>192.168.10.229</db_ip>    <db_name>nest_test</db_name>    <user_name>root</user_name>    <password>root</password>    <url>http://192.168.0.1:8080/SMSServer/SMSServlet</url>    <templateId>213047611111</templateId> </Settings>


2.XmlGlobal.java初始化

package xmlhelper;public class XmlGlobal {public static String Db_IP="";public static String User_Name="";public static String Pass_Word="";public static boolean  isConsolePro = false;public static String Db_Name="";public static String url="";public static String templateId="";}


3.GlobalXml.java读取文件赋值

package xmlhelper;import java.io.FileInputStream;import org.jdom.Document;import org.jdom.Element;import org.jdom.input.SAXBuilder;public class GlobalXml {public static void xmlParser(){try {String path="./resource/SysConfig/GlobalConfig.xml";FileInputStream fi=new FileInputStream(path);SAXBuilder builder = new SAXBuilder(false);Document read_doc = builder.build(fi);Element root = read_doc.getRootElement();XmlGlobal.Db_IP=root.getChild("db_ip").getValue();XmlGlobal.Db_Name=(root.getChild("db_name").getValue());XmlGlobal.User_Name=root.getChild("user_name").getValue();XmlGlobal.Pass_Word=root.getChild("password").getValue();XmlGlobal.url=root.getChild("url").getValue();XmlGlobal.templateId=root.getChild("templateId").getValue();} catch (Exception e) {e.printStackTrace();}}}
调用:
String id = XmlGlobal.templateId;


二、properties文件:

1.configure.properties配置文件

SMS_url=https://www.baidu.com/20141029AUTH_TOKEN=39cde072ec96APP_ID=32fd03c4db6444SERVER_IP=192.168.10.123:8080

2.ConfigureResource.java读取配置文件

package com.fisee.utils;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.InputStream;import java.util.PropertyResourceBundle;import java.util.ResourceBundle;public class ConfigureResource {private static ResourceBundle r;  private static InputStream in;static{  try   {      String path = System.getProperty("user.dir").replaceAll("\\\\", "/");      //System.out.println(path.replaceAll("bin", ""));in = new BufferedInputStream(new FileInputStream(path.replaceAll("bin", "")+"webapps/SMSServer/resource/configure.properties"));r = new PropertyResourceBundle(in); }   catch (Exception e)   {e.printStackTrace();}}        public static String getParam(String key)    {    try {    String s = new String(r.getString(key).getBytes("ISO-8859-1"),"GBK");    if(s.equalsIgnoreCase("SPACE")) s = " ";return s;} catch (Exception e) {System.out.println(e);return "Unknown";}    }        public static void main(String[] args) {System.out.println(ConfigureResource.getParam("SMS_url"));//取值}} 




0 0