一、Java程序中读取properties文件

加载的工具类: 

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; /**
* Properties工具类
* @author happyqing
* @since 2014.6.6
*/
public class PropertiesUtil {
private static final Log log = LogFactory.getLog(PropertiesUtil.class);
private static Properties env = new Properties(); static {
try {
//PropertiesHelper.class.getResourceAsStream("env.properties"); // /com/cici/conf/env.properties
//ClassLoader.getSystemResourceAsStream("env.properties");
InputStream is = PropertiesUtil.class.getClassLoader().getResourceAsStream("env.properties");
env.load(is);
is.close();
} catch (Exception e) {
log.error(e);
}
} /**
* 取属性值
* @param key
* @return
*/
public static String getProperty(String key){
return env.getProperty(key);
} /**
* 设置属性值
* @param key
* @param value
*/
public static void setProperty(String key, String value){
try{
File file = new File(PropertiesUtil.class.getClassLoader().getResource(".").getPath()+File.separator+"env.properties");
FileOutputStream outStream = new FileOutputStream(file);
env.setProperty(key, value);
//写入properties文件
env.store(outStream, null);
} catch (Exception ex) {
log.error(ex);
}
} public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(PropertiesUtil.getProperty("txtLength"));
//System.out.println(PropertiesUtil.class.getClassLoader().getResource(".").getPath());
}
}

  频繁的配置文件读取与操作,推荐apache commons大家庭的成员:commons-configuration

文件结构目录如图所示:

  其中,config2为与src同级的sourec folder,c.properties位于src根目录,b.properties位于src/config1 folder下

a.properties位于cn.package1包下。所有结果均已成功测试,测试环境为Myeclipse2016+JDK8

  其实以下也就是程序路径的区分

  1.读取a.properties:

 package cn.package1;

 import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import org.junit.Test; public class Demo01 {
@Test
public void fun1() throws IOException{
InputStream in1 = Demo01.class.getClassLoader()
.getResourceAsStream("cn/package1/a.properties");
Properties props = new Properties();
props.load(in1);
String value1 = props.getProperty("name");
System.out.println(value1);
}
}

(输入流的处理以及关闭可以改进)

  2.读取b.properties:

  (重复代码已经省略!)

 InputStream in1 = Demo01.class.getClassLoader()
.getResourceAsStream("config1/b.properties");

  3.读取c.properties:

 InputStream in1 = Demo01.class.getClassLoader()
.getResourceAsStream("c.properties");

  4.读取d.properties:

InputStream in1 = Demo01.class.getClassLoader()
.getResourceAsStream("d.properties");

二、Spring项目中读取properties

   总之就是,一定要加载到properties文件然后才能读取(xml文件读取或者java代码读取),至于加载的方式,可以是下面的直接使用context标签进行加载,例如使用classpath:*.properties(见下文配置文件),或者使用文末随笔中提到的使用spring的bean来进行加载!

   1.配置文件中使用——使用${}取值即可

  spring配置文件如何读取属性配置文件:

     <!-- 加载配置属性文件 -->
   <context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" />
   <!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />

  springMVC中进行配置:

  <!-- 加载配置属性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" /> <!-- 使用Annotation自动注册Bean,只扫描@Controller -->
<context:component-scan base-package="com.thinkgem.jeesite" use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

  // 必须注意,不使用默认的过滤器!

  2.Java代码中取值——使用@Value读取

/**
* 管理基础路径
*/
@Value("${adminPath}")
protected String adminPath; /**
* 前端基础路径
*/
@Value("${frontPath}")
protected String frontPath; /**
* 前端URL后缀
*/
@Value("${urlSuffix}")
protected String urlSuffix;

   // 像这里我们可以直接把它做成一个父类,这样每个类只需要继承父类便可使用此变量,而无须重复使用每个类的局部变量

  请谨记很多东西没必要写死的应该写在配置文件中,比如服务器的地址,数据库的密码等,不应该在程序中写死,而应该归配置文件管理!

   spring中读取配置文件也可以参见http://www.cnblogs.com/Gyoung/p/5507063.html

Properties读取小结的更多相关文章

  1. java properties读取与设值

    import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream; ...

  2. 关于java.util.Properties读取中文乱码的正确解决方案(不要再用native2ascii.exe了)

    从Spring框架流行后,几乎根本不用自己写解析配置文件的代码了,但近日一个基础项目(实在是太基础,不能用硕大繁琐的Spring), 碰到了用java.util.Properties读取中文内容(UT ...

  3. Properties读取properties配置文件

    package cn.rocker.readProperties; import java.io.IOException; import java.io.InputStream; import jav ...

  4. ResourceBundle与Properties读取配置文件

    ResourceBundle与Properties的区别在于ResourceBundle通常是用于国际化的属性配置文件读取,Properties则是一般的属性配置文件读取. ResourceBundl ...

  5. 解决使用Properties读取中文乱码问题

    web服务返回的是多行以key和value对应的键值对,且编码为utf-8.我的项目使用的编码也是utf-8,但是我用Properties读取中文的时候,打印出来的总是乱码. 后来网上查了一下,得到如 ...

  6. ResourceBundle和properties 读取配置文件区别

    java.util.ResourceBundle 和java.util.properties 读取配置文件区别 这两个类都是读取properties格式的文件的,而Properties同时还能用来写文 ...

  7. java.util.Properties 读取配置文件中的参数

    用法 getProperty方法的返回值是String类型. java.util.Properties 读取配置文件中的参数 //读取配置文件 FileInputStream inStream = n ...

  8. 【spring boot】SpringBoot初学(2.1) - properties读取明细

    前言 算是对<SpringBoot初学(2) - properties配置和读取>的总结吧. 概念性总结 一.Spring Boot允许外化(externalize)你的配置.可以使用pr ...

  9. Properties读取属性文件

    import java.util.*;import java.io.*;class PropertiesDemo{ public static void main(String[] args) thr ...

随机推荐

  1. leetCode题解之寻找一个数在有序数组中的范围Search for a Range

    1.问题描述 Given an array of integers sorted in ascending order, find the starting and ending position o ...

  2. September 11th 2017 Week 37th Monday

    I believe there is a hero in all of us. 我相信每个人心中都住着一个英雄. For every of us, there are two version with ...

  3. Python的multiprocessing,Queue,Process

    在多线程multiprocessing模块中,有两个类,Queue(队列)和Process(进程): 在Queue.py中也有一个Queue类,这两个Queue的区别? from multiproce ...

  4. BZOJ 1821 Group 部落划分 并查集

    题目链接: https://www.lydsy.com/JudgeOnline/problem.php?id=1821 题目大意: 聪聪研究发现,荒岛野人总是过着群居的生活,但是,并不是整个荒岛上的所 ...

  5. Ubuntu中文目录文件夹改为英文

    打开终端,在终端中输入命令: export LANG=en_US xdg-user-dirs-gtk-update 在弹出的窗口中询问是否将目录转化为英文路径,同意并关闭. 在终端中输入命令: exp ...

  6. 是否含有RTTI(运行时类型信息)是动态语言与静态语言的主要区别

    运行时类型信息代表类型信息和对内存的操作能力. 运行时类型信息是运行时系统的基础. 类型信息分为编译时类型信息和运行时类型信息两种: 静态语言的类型信息只在编译时使用和保留,在可执行文件中没有类型信息 ...

  7. hdu2824 The Euler function(欧拉函数个数)

    版权声明:本文为博主原创文章,未经博主同意不得转载. vasttian https://blog.csdn.net/u012860063/article/details/36426357 题目链接:h ...

  8. python里的splitlines具体解释

        Python的split方法函数能够切割字符串成列表,默认是以空格作为分隔符sep来切割字符串. In [1]: s = "www jeapedu com" In [2]: ...

  9. sql server 2000 错误229 拒绝了对象sysobjects 的select 权限

    此问题是权限问题,我的解决办法是因为添加角色的时候勾选太多导致的 !!!!!!千万不要勾选db_denydatareader.

  10. 你不知道的css高级应用三种方法——实现多行省略

    前言 这是个老掉牙的需求啦,不过仍然有很多人在网上找解决方案,特别是搜索结果排名靠前的那些,都是些只会介绍兼容性不好的使用-webkit-line-clamp的方案. 如果你看到这篇文章,可能代表你正 ...