Java加载properties文件的六种方法
java读取properties

at com.liuchen.getProperties.<clinit>(getProperties.java:16)
Exception in thread "main"
似乎config.load(in);这里的in是null,但有文件啊,这是怎么回事?谢谢!问题补充:
已经放在src目录了,但还是报那个错的
}
}
public static void main(String args[]) {
// String LaSaPhone=config.getProperty("LaSaPhone");
// System.out.println(LaSaPhone);
// System.out.println(getPhone.readValue("LaSaPhone"));
java读取properties文件
public class getProperties {
private static Properties config = null;
static {
InputStream in = getProperties.class.getClassLoader().getResourceAsStream(
"config.properties");
这一句换个写法试试:
Properties props = new Properties();
String url = this.getClass().getClassLoader().getResource(
Properties读取

java读取 .properties配置文件的几种方法java中的properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是 "键=值"的格式,在properties文件中,可以用"#"来作注释,properties文件在Java编程中用到的地方很多,操作很方便。
JDK中的Properties类存在于胞Java.util中,该类继承自Hashtable,它提供了几个主要的方法:1.getProperty(String key) 用指定的键在此属性列表中搜索属性。
也就是通过参数key ,得到key 所对应的value;2.load(InputStream inStream) 从输入流中读取属性列表(键和元素对)。
通过对指定的文件(如test.properties文件)进行装载来获取该文件中的所有键 - 值对。
以供getProperty(String key)来搜索。
3.setProperty(String key,String value),调用Hashtable的方法put。
他通过调用基类的put方法来设值键 - 值对。
4.store(OutputStream out,String comments),以适合使用load方法加载到Properties表中的格式,将此Properties表中的属性列表(键和元素对)写入输出流。
与load()方法相反,该方法将键 - 值对写入到指定的文件中去。
5.clear(),清除所有装载的键 - 值对。
该方法在基类中提供。
方式一使用java.util.Properties类的load()方法关键代码如下:try{// 创建Properties对象Properties p = new Properties();// 设置读取文件路径String s_xmlpath="config.properties";InputStream io=Test.class.getClassLoader().getResourceAsStream(s_xmlpath);// 加载文件p.load(io);// 取得文件的值system.out.println(p.getProperty("key"));// 关闭流io.close();}catch(Exception ex){ex.printStackTrace();}该方法可放到Servlet中,在工程初期化时一次性加载配置文件,具体代码如下:import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.Properties;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class Test extends HttpServlet {public static Properties p;private static Test instance = null;/*** Constructor of the object.* 默认构造方法*/public Test() {super();}/*** Constructor of the object.* 私有构造方法,调用init()方法读取配置文件*/private Test(String str) {super();try {this.init();} catch (ServletException e) {e.printStackTrace();}/*** 静态方法,取得对象实例* @return*/public static Test getInstance(){// 当前实例为空时if(instance == null){instance = new Test("");}return instance;}/*** Destruction of the servlet. <br>*/public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/*** The doGet method of the servlet. <br>* This method is called when a form has its tag value method equals to get.*/public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {……}/*** The doPost method of the servlet. <br>* This method is called when a form has its tag value method equals to post.*/public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {……}/*** Initialization of the servlet. <br>* @throws ServletException if an error occurs*/public void init() throws ServletException {try{// 创建Properties对象p = new Properties();// 设置读取文件路径String s_xmlpath="sql.properties";InputStream io=Test.class.getClassLoader().getResourceAsStream(s_xmlpath);// 加载文件p.load(io);// 关闭流io.close();}catch(Exception ex){ex.printStackTrace();}}}在工程的web.xml文件中添加以下配置:<description>This is the description of my J2EE component</description><display-name>This is the display name of my J2EE component</display-name><servlet-name>Test</servlet-name><servlet-class>com.Test</servlet-class><load-on-startup>1</load-on-startup></servlet>经过以上配置,可以通过Test类的静态属性读取配置文件中的值。
java获取配置文件的参数的方法

一、概述Java是一种流行的编程语言,广泛应用于企业级软件开发。
在Java应用程序中,经常需要读取配置文件中的参数,以便程序在不同环境下能够灵活运行。
本文将介绍在Java中获取配置文件参数的方法。
二、使用Properties类在Java中,可以使用Properties类来读取配置文件。
Properties是HashTable的子类,它用于处理键值对形式的配置信息。
下面是使用Properties类获取配置文件参数的步骤:1. 创建Properties对象首先使用Properties类创建一个对象,用于存储配置文件中的参数。
可以通过以下代码实现:```javaProperties props = new Properties();```2. 加载配置文件接下来,需要将配置文件加载到Properties对象中。
通常配置文件的格式是.properties,可以通过以下代码加载:```javatry{InputStream inputStream =getClass().getClassLoader().getResourceAsStream("config.prope rties");props.load(inputStream);}catch(IOException e){e.printStackTrace();}```上述代码中,使用ClassLoader的getResourceAsStream方法加载配置文件,并使用Properties的load方法将文件内容加载到props 对象中。
3. 获取参数值一旦配置文件加载到props对象中,就可以通过getProperty方法获取参数值。
获取名为"db.url"的参数值可以使用以下代码:```javaString dbUrl = props.getProperty("db.url");```通过上述步骤,就可以在Java中轻松获取配置文件中的参数值了。
JAVAProperties配置文件的读写

JAVAProperties配置⽂件的读写 通常我们就会看到⼀个配置⽂件,⽐如:jdbc.properties,它是以“.properties”格式结尾的。
在java中,这种⽂件的内容以键值对<key,value>存储,通常以“=”分隔key和value,当然也可以⽤":"来分隔,但通常不这么⼲。
读取配置⽂件 这⾥有⼀个⽂件叫asfds.properties,⾥⾯简单的存了两个键值对,如下图所⽰: 读取配置⽂件的基本步骤是:1. 实例化⼀个Properties对象;2. 将要读取的⽂件放⼊数据流中;3. 调⽤Properties对象的load⽅法,将属性⽂件的键值对加载到Properties类对象中;4. 调⽤Properties对象的getProperty(String key)读⼊对应key的value值。
注:如果想要读取key值,可以调⽤Properties对象的stringPropertyNames()⽅法获取⼀个set集合,然后遍历set集合即可。
读取配置⽂件的⽅法: 1/**2 * read properties file3 * @param paramFile file path4 * @throws Exception5*/6public static void inputFile(String paramFile) throws Exception7 {8 Properties props=new Properties();//使⽤Properties类来加载属性⽂件9 FileInputStream iFile = new FileInputStream(paramFile);10 props.load(iFile);1112/**begin*******直接遍历⽂件key值获取*******begin*/13 Iterator<String> iterator = props.stringPropertyNames().iterator();14while (iterator.hasNext()){15 String key = iterator.next();16 System.out.println(key+":"+props.getProperty(key));17 }18/**end*******直接遍历⽂件key值获取*******end*/1920/**begin*******在知道Key值的情况下,直接getProperty即可获取*******begin*/21 String user=props.getProperty("user");22 String pass=props.getProperty("pass");23 System.out.println("\n"+user+"\n"+pass);24/**end*******在知道Key值的情况下,直接getProperty即可获取*******end*/25 iFile.close();2627 }写⼊配置⽂件 写⼊配置⽂件的基本步骤是:1. 实例化⼀个Properties对象;2. 获取⼀个⽂件输出流对象(FileOutputStream);3. 调⽤Properties对象的setProperty(String key,String value)⽅法设置要存⼊的键值对放⼊⽂件输出流中;4. 调⽤Properties对象的store(OutputStream out,String comments)⽅法保存,comments参数是注释; 写⼊配置⽂件的⽅法:1/**2 *write properties file3 * @param paramFile file path4 * @throws IOException5*/6private static void outputFile(String paramFile) throws IOException {7///保存属性到b.properties⽂件8 Properties props=new Properties();9 FileOutputStream oFile = new FileOutputStream(paramFile, true);//true表⽰追加打开10 props.setProperty("testKey", "value");11//store(OutputStream,comments):store(输出流,注释) 注释可以通过“\n”来换⾏12 props.store(oFile, "The New properties file Annotations"+"\n"+"Test For Save!");13 oFile.close();14 }测试输出 ⽂件读取: @Testpublic void testInputFile(){//read properties filetry {inputFile("resources/asfds.properties");} catch (Exception e) {e.printStackTrace();}} 输出: ⽂件写⼊:@Testpublic void testOutputFile(){//write properties filetry {outputFile("resources/test.properties");} catch (Exception e) {e.printStackTrace();}} 写⼊的⽂件:。
Java程序读取配置文件的几种方法

Java程序读取配置⽂件的⼏种⽅法Java 开发中,需要将⼀些易变的配置参数放置再 XML 配置⽂件或者 properties 配置⽂件中。
然⽽ XML 配置⽂件需要通过 DOM 或 SAX ⽅式解析,⽽读取 properties 配置⽂件就⽐较容易。
1. 读取properties⽂件的⽅法1. 使⽤类加载器ClassLoder类读取配置⽂件InputStream in = MainClass.class.getClassLoader().getResourceAsStream("com/demo/config.properties");MainClass.class是主类的反射对象,因为getClassLoader()是class类的对象⽅法。
在类加载器中调⽤getResourceAsStream()时,采⽤相对路径,起始位置在src⽬录,路径开头没有“/”。
InputStream in = (new MainClass()).getClass().getClassLoader().getResourceAsStream("com/demo/config.properties");因为getClass()是object类的对象⽅法,所有在主类调⽤时要将主类实体化,即new MainClass()。
同理,相对路径起始位置同上。
2. ⽤class对象读取配置⽂件之所以Class对象也可以加载资源⽂件是因为Class类封装的getResourceAsStream⽅法的源码中调⽤了类加载器。
InputStream in = MainClass.class.getResourceAsStream(“/com/demo/config.properties”);同样MainClass.class是主类的反射对象。
在class对象中调⽤getResourceAsStream()时,采⽤绝对路径,起始位置在类路径(bin⽬录),因此路径要以“/”开头。
五种方式让你在java中读取properties文件内容不再是难题

五种⽅式让你在java中读取properties⽂件内容不再是难题 最近,在项⽬开发的过程中,遇到需要在properties⽂件中定义⼀些⾃定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题。
就借此机会把Spring+SpringMVC+Mybatis整合开发的项⽬中通过java程序读取properties⽂件内容的⽅式进⾏了梳理和分析,现和⼤家共享。
Spring 4.2.6.RELEASESpringMvc 4.2.6.RELEASEMybatis 3.2.8Maven 3.3.9Jdk 1.7Idea 15.04⽅式1.通过context:property-placeholder加载配置⽂件jdbc.properties中的内容<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/> 上⾯的配置和下⾯配置等价,是对下⾯配置的简化<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="ignoreUnresolvablePlaceholders" value="true"/><property name="locations"><list><value>classpath:jdbc.properties</value></list></property></bean>注意:这种⽅式下,如果你在spring-mvc.xml⽂件中有如下配置,则⼀定不能缺少下⾯的红⾊部分,关于它的作⽤以及原理,参见另⼀篇博客:<!-- 配置组件扫描,springmvc容器中只扫描Controller注解 --><context:component-scan base-package="com.hafiz.www" use-default-filters="false"><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan>⽅式2.使⽤注解的⽅式注⼊,主要⽤在java代码中使⽤注解注⼊properties⽂件中相应的value值<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean"><!-- 这⾥是PropertiesFactoryBean类,它也有个locations属性,也是接收⼀个数组,跟上⾯⼀样 --><property name="locations"><array><value>classpath:jdbc.properties</value></array></property></bean>⽅式3.使⽤util:properties标签进⾏暴露properties⽂件中的内容<util:properties id="propertiesReader" location="classpath:jdbc.properties"/>注意:使⽤上⾯这⾏配置,需要在spring-dao.xml⽂件的头部声明以下红⾊的部分<beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:context="/schema/context"xmlns:util="/schema/util"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.2.xsd/schema/context/schema/context/spring-context-3.2.xsd/schema/util /schema/util/spring-util.xsd">⽅式4.通过PropertyPlaceholderConfigurer在加载上下⽂的时候暴露properties到⾃定义⼦类的属性中以供程序中使⽤<bean id="propertyConfigurer" class="com.hafiz.www.util.PropertyConfigurer"><property name="ignoreUnresolvablePlaceholders" value="true"/><property name="ignoreResourceNotFound" value="true"/><property name="locations"><list><value>classpath:jdbc.properties</value></list></property></bean>⾃定义类PropertyConfigurer的声明如下:package com.hafiz.www.util;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;import java.util.Properties;/*** Desc:properties配置⽂件读取类* Created by hafiz.zhang on 2016/9/14.*/public class PropertyConfigurer extends PropertyPlaceholderConfigurer {private Properties props; // 存取properties配置⽂件key-value结果@Overrideprotected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)throws BeansException {super.processProperties(beanFactoryToProcess, props);this.props = props;}public String getProperty(String key){return this.props.getProperty(key);}public String getProperty(String key, String defaultValue) {return this.props.getProperty(key, defaultValue);}public Object setProperty(String key, String value) {return this.props.setProperty(key, value);}}使⽤⽅式:在需要使⽤的类中使⽤@Autowired注解注⼊即可。
Java获取properties的几种方式

Java获取properties的⼏种⽅式⽬录第1种:直接在spring的xml中使⽤第2种:在java 启动加Conifg库中或者在controller中调⽤第3种:不要在spring.xml中引⽤commonConfig.properties,在类注⼊时引⽤,然后使⽤Environment获取它的值第4种:不需要借⽤spring,直接在类中读取.但要注意:(redisson.properties配置⽂件中不能有.句号),否则将报错spring下获取Properties⽅式⽐如已有的commonConfig.propertiesmain.db.driverClassName=com.mysql.jdbc.Drivermain.db.url=jdbc\:mysql\://\:3306/huagang?useUnicode\=true&characterEncoding\=UTF-8&zeroDateTimeBehavior\=convertToNullername=huagangmain.db.password=xxxHGtest在spring中引⽤commonConfig.properties第1种:直接在spring的xml中使⽤<!-- 加载配置⽂件 --><bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location"><value>classpath:/resources/config/commonConfig.properties</value></property></bean> <!--或者引⼊多配置⽂件<context:property-placeholder location="classpath:/resources/config/commonConfig.properties,classpath:XXX.properties"/> --><!-- 配置数据源 --><bean id="ajbDataSource" class="boPooledDataSource" destroy-method="close"><!--驱动类 --><property name="driverClass"><value>${main.db.driverClassName}</value></property><!--url连接串 --><property name="jdbcUrl"><value>${main.db.url}</value></property><!--⽤户名 --><property name="user"><value>${ername}</value></property><!--密码 --><property name="password"><value>${main.db.password}</value></property><!-- 连接池中保留的最⼩连接数最⼩链接数 --><property name="minPoolSize"><value>1</value></property><!--连接池中保留的最⼤连接数最⼤连接数 --><property name="maxPoolSize"><value>4</value></property><!-- 最⼤空闲的时间,单位是秒,⽆⽤的链接再过时后会被回收 --><property name="maxIdleTime"><value>1800</value></property><!-- 在当前连接数耗尽的时候,⼀次获取的新的连接数 --><property name="acquireIncrement"><value>1</value></property><!--JDBC的标准参数,⽤以控制数据源内加载的PreparedStatements数量。
properties类的load方法

properties类的load方法
Properties 类的load方法是指 Java 提供的一个方法,用于读取属性文件并将内容加载到 Properties 对象中,以便更方便的处理和读取数据。
1、load方法能够加载属性文件中文件的性质,它只能将文件加载到 Properties 对象中,无法将复杂的文件结构读取到 Properties 对象中;
2、load方法支持三种文件格式,分别是.txt、.ini、.xml,文件内容可以是普通字符文本文件;
3、load方法在加载属性文件时,会将文件中的内容转换为键值对,方便后续通过键值对中的key获取指定的属性值;
4、使用load方法加载的属性文件是不能修改的,因此,2015.10.27只能被用来读取属性文件的内容,不能用于修改和更新属性文件的内容;
5、load方法可以从文件、流中加载属性文件,也可以从应用程序中加载,通过输入字符串数组等方式加载;
6、load方法是一种不太推荐使用的方法,它只是 Properties 的一个静态函数,它本身在多线程环境中并不安全;
7、Properties 类的load方法的作用是:属性文件的信息由键值组成,load方法可以将这种格式的文件加载到 Properties 对象中,以将文件的内容读取出来,从而可以根据键名获取该键对应的值。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
p.load(in);
完整的示例,可以参考附件文件 如何上传文件,谁知道请告诉以下。 只好把 source 都贴上来了 JProperties.java 文件
package com.kindani;
//import javax.servlet.ServletContext; import java.util.*; import java.io.InputStream; import java.io.IOException; import java.io.BufferedInputStream; import java.io.FileInputStream;
private ResourceBundle rb = null;
public ResourceBundle getBundle(String baseName) { return ResourceBundle.getBundle(baseName); }
public ResourceBundle getBundle(String baseName, Locale locale) { return ResourceBundle.getBundle(baseName, locale); }
public class JPropertiesTest extends TestCase { JProperties jProperties; String key = "helloworld.title"; String value = "Hello World!";
public void testLoadProperties() throws Exception { String name = null; Properties p = new Properties();
if (in != null) {
in.close(); } return p;
}
// ---------------------------------------------- servlet used
// ---------------------------------------------- support class
}
}
JPropertiesTest.java 文件
package com.kindani.test;
import junit.framework.*; import com.kindani.JProperties;
//import javax.servlet.ServletContext; import java.util.Properties;
public String[] getStringArray(String key) { return rb.getStringArray(key); }
protected Object handleGetObject(String key) { return ((PropertyResourceBundle) rb).handleGetObject(key); }
public ResourceBundle getBundle(String baseName, Locale locale, ClassLoader loader) { return ResourceBundle.getBundle(baseName, locale, loader); }
public Enumeration getKeys() { return rb.getKeys(); }
6。使用 ng.ClassLoader 类的 getSystemResourceAsStream()静态方 法 示例:InputStream in = ClassLoader.getSystemResourceAsStream(name); Properties p = new Properties(); p.load(in);
public final static Properties loadProperties(final String name, final int type) throws IOException { Properties p = new Properties(); InputStream in = null; if (type == BY_PROPERTIES) { in = new BufferedInputStream(new FileInputStream(name)); assert (in != null); p.load(in); } else if (type == BY_RESOURCEBUNDLE) { ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault()); assert (rb != null); p = new ResourceBundleAdapter(rb); } else if (type == BY_PROPERTYRESOURCEBUNDLE) { in = new BufferedInputStream(new FileInputStream(name)); assert (in != null); ResourceBundle rb = new PropertyResourceBundle(in);
2。使用 java.util.ResourceBundle 类的 getBundle()方法 示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
3。使用 java.util.PropertyResourceBundle 类的构造函数 示例: InputStream in = new BufferedInputStream(new FileInputStream(name)); ResourceBundle rb = new PropertyResourceBundle(in);
p = new ResourceBundleAdapter(rb); } else if (type == BY_CLASS) { assert (JProperties.class.equals(new JProperties().getClass())); in = JProperties.class.getResourceAsStream(name); assert (in != null); p.load(in); // return new JProperties().getClass().getResourceAsStream(name); } else if (type == BY_CLASSLOADER) { assert (JProperties.class.getClassLoader().equals(new JProperties().getClass().getClassLoader())); in = JProperties.class.getClassLoader().getResourceAsStream(name); assert (in != null); p.load(in); // return new JProperties().getClass().getClassLoader().getResourceAsStream(name); } else if (type == BY_SYSTEM_CLASSLOADER) { in = ClassLoader.getSystemResourceAsStream(name); assert (in != null); p.load(in); }
补充
Servlet 中可以使用 javax.servlet.ServletContext 的 getResourceAsStream() 方法 示例:InputStream in = context.getResourceAsStream(path); Properties p = new Properties();
public Locale getLocale() { return rb.getLocale();
}
public Object getObject(String key) { return rb.getObject(key); }
public String getString(String key) { return rb.getString(key); }
public class JProperties {
public final static int BY_PROPERTIES = 1; public final static int BY_RESOURCEBUNDLE = 2;
public final static int BY_PROPERTYRESOURCEBUNDLE = 3; public final static int BY_CLASS = 4; public final static int BY_CLASSLOADER = 5; public final static int BY_SYSTEM来自CLASSLOADER = 6;
public static class ResourceBundleAdapter extends Properties { public ResourceBundleAdapter(ResourceBundle rb) { assert (rb instanceof java.util.PropertyResourceBundle); this.rb = rb; java.util.Enumeration e = rb.getKeys(); while (e.hasMoreElements()) { Object o = e.nextElement(); this.put(o, rb.getObject((String) o)); } }