Java之properties文件读取

来源:互联网 发布:h3c网络工程师证书知乎 编辑:程序博客网 时间:2024/06/04 18:02

1、工程结构

2、ConfigFileTest.java

复制代码
package com.configfile;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration;import java.util.Properties;public class ConfigFileTest {        private static Properties config = null;    static {         InputStream in = ConfigFileTest.class.getClassLoader().getResourceAsStream("parameter.properties");         config = new Properties();               try {           config.load(in);           in.close();         } catch (IOException e) {           //读取url.properties出错           e.printStackTrace();        }      }         /**      * 通过键获得对应的值      * @param key      * @return      */    public static String getValue(String key) {     try {      String value = config.getProperty(key);      return value.trim();     } catch (Exception e) {      e.printStackTrace();       return null;     }    }    /**     * 读取properties的全部信息     */    public static void getAllProperties() {     try {      Enumeration en = config.propertyNames();      while (en.hasMoreElements()) {       String key = (String) en.nextElement();       String Property = config.getProperty(key);       System.out.println("key = "+config.getProperty(key));      }     } catch (Exception e) {       e.printStackTrace();       System.err.println("ConfigInfoError" + e.toString());     }    }
public static void main(String args[]) { System.out.println(getValue("title")); getAllProperties(); }}
复制代码

注:1、properties类详解见:Java中Properties类的操作、JAVA操作properties文件

  2、getClass():取得当前对象所属的Class对象   
       getClassLoader():取得该Class对象的类装载器
       类装载器负责从Java字符文件将字符流读入内存,并构造Class类对象,在你说的问题哪里,通过它可以得到一个文件的输入流
3、parameter.properties

title=\u4E2D\u56FD\u4F60\u597D ##爱你中国message=\u6211\u6765\u4E86  ##我来了
0 0
原创粉丝点击