java代码和spring框架读取xml和properties文件

时间:2022-05-11 02:12:52

1.java文件读取properties文件

 Properties props = new Properties();
try {
//资源文件存放在类文件的根目录下。即是放在src下面。则不需要写路
      //径,此时是放在file文件夹下
props.load(getClass().getClassLoader().getResourceAsStream(
"file/user.properties"));
//当资源文件中有中文的时候可以采用下面的编码转化方法来读取。
//然后直接读取props.getProperty("name");
System.out.println(new String(props.getProperty("name").getBytes(
"ISO-8859-1"), "GBK"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

2.java读取xml文件

try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(new File("d://asp-search-config.xml"));
Element elmtInfo = doc.getDocumentElement();
NodeList nodes = elmtInfo.getChildNodes();
int m = 1;
System.out.println(nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++)
{
Node result = nodes.item(i);
System.out.println(result.getNodeType()+"----"+result.getNodeName());
if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("index-file"))
{
NodeList ns = result.getChildNodes(); for (int j = 0; j < ns.getLength(); j++)
{
Node record = ns.item(j);
System.out.println(record.getNodeType()+"@@@@"+record.getNodeName());
if (record.getNodeType() == Node.ELEMENT_NODE && record.getNodeName().equals("path"))
{
System.out.println(m + ": " + record.getTextContent());
m++;
}
}
}
}
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

第二种方法:

 // 使用了dom4j解析xml
// 读取目录下用来测试的*.xml文件,取得xml主内容
SAXReader saxReader = new SAXReader();
Document document = saxReader.read("d://asp-search-config.xml").getDocument();
int i = 1;
// 遍历文档根节点(wuxialist)下的子节点列表,即txtbook节点的集合
     //document.getRootElement()获取根节点asp-search-config
for(Element txtbook : (List<Element>)document.getRootElement().elements()){
//取得txtbook节点下的name节点的内容
System.out.println(i+"."+txtbook.element("path").getText());
}

3.运用spring读取xml文件

 1.利用ClassPathXmlApplicationContext
  ApplicationContext context = new ClassPathXmlApplicationContext("beanConfig.xml");
//这种用法不够灵活,不建议使用。
HelloBean helloBean = (HelloBean)context.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
2.利用FileSystemResource读取
Resource rs = new FileSystemResource("D:/software/tomcat/webapps/springWebDemo/WEB-INF/classes/beanConfig.xml");
BeanFactory factory = new XmlBeanFactory(rs);
HelloBean helloBean = (HelloBean)factory.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
值得注意的是:利用FileSystemResource,则配置文件必须放在project直接目录下,或者写明绝对路径,否则就会抛出找不到文件的异常。

4.运用spring读取properties文件

我们还利用上面的HelloBean.java文件,构造如下beanConfig.properties文件:

helloBean.class=chb.demo.vo.HelloBean

helloBean.helloWorld=Hello!chb!

    属性文件中的"helloBean"名称即是Bean的别名设定,.class用于指定类来源。

    然后利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件

  BeanDefinitionRegistry reg = new DefaultListableBeanFactory();

  PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);

  reader.loadBeanDefinitions(new ClassPathResource("beanConfig.properties"));

  BeanFactory factory = (BeanFactory)reg;

  HelloBean helloBean = (HelloBean)factory.getBean("helloBean");

  System.out.println(helloBean.getHelloWorld());

5.判断名字为name的cookie是否存在,存在则得到该cookie的值,不存在则创建出值为“程序员”的cookie

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
Cookie[] cookies = request.getCookies();
boolean flag = false ;
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals("name")) {
out.print("<h2>exist , "+URLDecoder.decode(cookie.getValue(),"utf-8")+"</h2>");
flag = true ;
break;
}
if (!flag) {
Cookie cookieAdd = new Cookie("name", URLEncoder.encode("程序员","utf-8"));
response.addCookie(cookieAdd);
out.print("<h2>not exist , create successfully</h2>");
}
}
}else{
Cookie cookieAdd = new Cookie("name", URLEncoder.encode("程序员","utf-8"));
response.addCookie(cookieAdd);
out.print("<h2>no one exist,create successfully</h2>");
}
out.close();
}