java代码和spring框架读取xml和properties文件
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();
    }
java代码和spring框架读取xml和properties文件的更多相关文章
- 【Java编程】写入、读取、遍历Properties文件
		
在Java开发中通常我们会存储配置參数信息到属性文件.这种属性文件能够是拥有键值对的属性文件,也能够是XML文件.关于XML文件的操作,请參考博文[Java编程]DOM XML Parser 解析.遍 ...
 - spring 框架的xml文件如何读取properties文件数据
		
spring 框架的xml文件如何读取properties文件数据 第一步:在spring配置文件中 注意:value可以多配置几个properties文件 <bean id="pro ...
 - Java 横向技术 Spring框架【笔记】
		
Java横向技术 spring框架[笔记] Spring 的两大特性是什么? AOP(Aspect Oriented Programming,面向切面编程)与 IOC(Inverse of Contr ...
 - 基于纯Java代码的Spring容器和Web容器零配置的思考和实现(3) - 使用配置
		
经过<基于纯Java代码的Spring容器和Web容器零配置的思考和实现(1) - 数据源与事务管理>和<基于纯Java代码的Spring容器和Web容器零配置的思考和实现(2) - ...
 - 跟着刚哥学习Spring框架--通过XML方式配置Bean(三)
		
Spring配置Bean有两种形式(XML和注解) 今天我们学习通过XML方式配置Bean 1. Bean的配置方式 通过全类名(反射)的方式 √ id:标识容器中的bean.id唯一. √ cl ...
 - java如何读取和遍历properties文件
		
在java项目开发过程中,使用properties文件作为配置基本上是必不可少的,很多如系统配置信息,文件上传配置信息等等都是以这种方式进行保存.同时学会操作properties文件也是java基础. ...
 - 【Java】关于Spring框架的总结 (一)
		
本文总结一些关于Spring框架的理解,注意点及基础操作.如果有不对的地方,欢迎批评和建议.大家一起努力吧! Spring 框架简介 Spring 是一个开源框架,是为了解决企业应用程序开发复杂性而创 ...
 - 【Java】关于Spring框架的总结 (三)
		
前文对 Spring IoC 和 Spring AOP 的实现方法进行了整合.如果有不明白的或有质疑的地方可以评论出来,一起探讨问题,帮助别人也是帮助自己!本文探讨的中心主要放在 Spring 的注解 ...
 - Spring如何读取xml配置文件的
		
我们通过一个小案例来看xml解析过程. 1. 导包 <dependencies> <!-- xml解析工具 --> <dependency> <groupId ...
 
随机推荐
- ORACLE查看并修改session和连接最大数
			
第一步,在cmd命令行,输入sqlplus 第二步,根据提示输入用户名与密码 1. 查看processes和sessions参数 SQL> show parameter processes NA ...
 - iocp还是select
			
上一个项目libevent应该是select,现在libuv是iocp,都知道Windows下iocp比select效率高,boost asio 也是iocp,但具体使用select和iocp发现没有 ...
 - centos linux安装telnet 过程及问题(源于内部tomcat网站,外部无法访问)
			
首先本地没有telnet客户端及服务器 root权限下安装 yum install telnet yum install telnet-server vi /etc/xinetd.d/telnet 这 ...
 - LyX-220-Installer-3
			
所见即所得 单独安装这个写作业可以了,要发论文用CTeX Ctrl + M 打开数学输入,里面可以输入 TeX 代码
 - css3 中的transition和transform
			
我以前始终都把他搞反,或者是混淆.现在可以稍微小结下. Transition:CSS3中处理动画的一个样式:只涉及动画起始和终止两个状态.如果涉及到一个动画的各个时间或者状态,那就必须要用到的另外一个 ...
 - Envelope Letter
			
http://www.thefullwiki.org/More_C%2B%2B_Idioms/Envelope_Letter http://www.smallmemory.com/almanac/Co ...
 - PHP7的安装
			
PHP7和HHVM比较PHP7的在真实场景的性能确实已经和HHVM相当, 在一些场景甚至超过了HHVM.HHVM的运维复杂, 是多线程模型, 这就代表着如果一个线程导致crash了, 那么整个服务就挂 ...
 - python 计算器的(正则匹配+递归)
			
经过2天的长时间的战斗,python计算器终于完成了. import re val="1-2*((60-30*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3 ...
 - 在虚机中安装CentOS
			
摘要 最近看到.net core 1发布的内容,也想尝试着在lunix上跑一圈.linux这方面的知识一直都没怎么接触过,只在工作中见同事操作过,看到满屏幕的命令行,感觉非常的高大上,趁着现在赶紧学习 ...
 - echo '.SUFFIXES: .cpp' >> ${OUTPUT_FILE}
			
当前makefile或shell内支持文件后缀的类型列表,意思是文件支持.cpp结尾的类型,并且将他,输出到OUTPUT_FILE函数. 见网上有人说: “makefile中 .SUFFIXES: . ...