//加载文件
public static void testLoadProperties() throws Exception {
Properties properties = new Properties(); InputStream in = new FileInputStream("E:/itcast/config.properties");
properties.load(in); // 加载
in.close(); System.out.println(properties);
}
//写配置文件
public static void testStoreProperties() throws Exception { // 准备配置信息 Properties properties = new Properties(); properties.setProperty("name", "李四"); properties.setProperty("age", "20"); // 准备 OutputStream out = new FileOutputStream("d:/my.properties"); String comments = "这是我的配置文件"; // 写出去 properties.store(out, comments); out.close(); }

 
 
static Properties properties ;

    static{
try {
properties = new Properties();
Class clazz = dd.class;
InputStream inputStream = clazz.getResourceAsStream("/my.properties"); // "/"������Classpath��·���� getResourceAsStream �÷�������ʹ�õ�·������ʹ�������ļ�·����
properties.load(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public static void main(String[] args) {
System.out.println("��ǰ·����"+ new File(".").getAbsolutePath() );
System.out.println( properties.getProperty("userName")+":"+properties.getProperty("password")); }

Properties类对应.properties文件。文件内容是键值对,键值对之间使用"="或空格隔开。开头是"#"的表示注释

Properties类在加载.properties文件时使用的iso8859-1的编码。所以这个文件中的中文要特殊处理:如果这个配置文件中有中文就必须要进行转义,使用native2ascii.exe命令操作:

native2ascii d:/my.properties d:/my2.properties

使用Properties类中的load(InputStream) 方法可以加载配置文件,使用其中的store(OutputStream) 方法可以保存配置到指定文件。

更多的信息可以看Properties类的API文档。

/**
* 1. getRealPath读取,返回资源文件的绝对路径
*/
/*String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
System.out.println(path);
File file = new File(path);
FileInputStream in = new FileInputStream(file);*/ /**
* 2. getResourceAsStream() 得到资源文件,返回的是输入流
*/
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties prop = new Properties();
//读取资源文件
prop.load(in); String user = prop.getProperty("user");
String password = prop.getProperty("password");
System.out.println("user="+user);
System.out.println("password="+password); }

最新文章

  1. atitit.管理学三大定律:彼得原理、墨菲定律、帕金森定律
  2. hibernate_Restrictions用法
  3. shell 简单计算脚本
  4. Moqui简介
  5. LINUX下安装PHP(CGI模式)和NGINX[转]
  6. js前台与后台数据交互-前台调后台
  7. const详解
  8. Count Primes ——LeetCode
  9. 深入解析MySQL视图view
  10. hibernate的操作Blob和Clob类型数据(笔记)
  11. axure授权码
  12. 基于Emgucv,C#的图片旋转方式
  13. jieba(杰巴)分词的三种模式
  14. 解决反射型XSS漏洞攻击
  15. Innodb引擎中Count(*)
  16. PHP的SQL语句优化
  17. Egret引擎的常用倒计时
  18. C#中对Web.Config、App.Config字符串加密与解密的方法
  19. 自定义Exception:MVC抛出自定义异常,并以Json方式返回
  20. sqlite c#

热门文章

  1. CDS & ORF & 启动子 & 终止子 & 转录因子 & 基因结构 & UTR
  2. ACM/ICPC 2018亚洲区预选赛北京赛站网络赛
  3. C++&C#外挂(内存修改)
  4. UVA-11149 Power of Matrix(矩阵二分幂)
  5. 手动安装Silverlight 4 Tools for Visual Studio 2010
  6. Pl/sql Dev登录数据库查询报ORA-03114
  7. Vim:replace with foobar (y/n/a/q/l/^E/^Y)?
  8. 46. 47. Permutations
  9. quartz---的Scheduler
  10. OC MRC之set方法内存管理(代码分析)