读取properties配置文件|如何在spring中读取properties配置文件里面的信息

读取properties配置文件|如何在spring中读取properties配置文件里面的信息的第1张示图

❶ java程序读取properties配置文件出现中文乱码

你的properties文件编译过了吗?凡是有非西欧的字符都应该事先编译的,具体方法如下:比如你有一个1.properties文件(含有非西欧字符),你可以在cmd窗口中切换到1.properties文件所在目录,然后输入native2ascii -reverse -encoding gb2312 1.properties ActionName_zh_CN.properties1.properties为转换之前的文件名 ActionName_zh_CN.properties为转换之后的文件名,其中-encoding后面的gb2312是可以变的如 utf-8等

❷ 如何在spring中读取properties配置文件里面的信息

一般来说。我们会将一些配置的信息放在。properties文件中。 然后使用${}将配置文件中的信息读取至spring的配置文件。 那么我们如何在spring读取properties文件呢。 1.首先。我们要先在spring配置文件中。定义一个专门读取properties文件的类. 例: <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:jdbc.properties</value> <!–要是有多个配置文件,只需在这里继续添加即可 –> </list> </property> </bean> 这里为什么用locations(还有一个location) 是因为。一般来说。我们的项目里面。配置文件可能存在多个。 就算是只有一个。那将来新添加的话。只需在下面再加一个value标签即可。 而不必再重新改动太多。(当然。性能上是否有影响,这个以当前这种服务器的配置来说。是基科可以忽略不计的)。 然后我们就可以在jdbc.properties文件中填写具体的配置信息了。 <!– 配置C3P0数据源 –> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${jdbc.driverClassName}</value> </property> <property name="jdbcUrl"> <value>${jdbc.url}</value> </property> <property name="user"> <value>${jdbc.username}</value> </property> <property name="password"> <value>${jdbc.password}</value> </property> </bean> jdbc.properties文件写的信息。 jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=root 附加一个列子: <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>file:/data/pc-config/passport.properties</value> <value>classpath:memcached.properties</value> </list> </property> </bean> classpath:是指的当前类文件的目录下。 file:在window下是指的当前分区(比如你的项目是放在d盘,则是在d:/data/pc-config/passport.properties) 在linux下,则是当前路径下的文件/data/pc-config/passport.properties 转载仅供参考,版权属于原作者。祝你愉快,满意请~~哦

❸ 如何从Properties配置文件读取值

最常用读取properties文件的方法InputStream in = getClass().getResourceAsStream("资源Name");这种方式要求properties文件和当前类在同一文件夹下面。如果在不同的包中,必须使用:InputStream ins = this.getClass().getResourceAsStream("/cn/zhao/properties/testPropertiesPath2.properties");Java中获取路径方法获取路径的一个简单实现反射方式获取properties文件的三种方式1 反射方式获取properties文件最常用方法以及思考:Java读取properties文件的方法比较多,网上最多的文章是"Java读取properties文件的六种方法",但在Java应用中,最常用还是通过java.lang.Class类的getResourceAsStream(String name) 方法来实现,但我见到众多读取properties文件的代码中,都会这么干:InputStream in = getClass().getResourceAsStream("资源Name");这里面有个问题,就是getClass()调用的时候默认省略了this!我们都知道,this是不能在static(静态)方法或者static块中使用的,原因是static类型的方法或者代码块是属于类本身的,不属于某个对象,而this本身就代表当前对象,而静态方法或者块调用的时候是不用初始化对象的。问题是:假如我不想让某个类有对象,那么我会将此类的默认构造方法设为私有,当然也不会写别的共有的构造方法。并且我这个类是工具类,都是静态的方法和变量,我要在静态块或者静态方法中获取properties文件,这个方法就行不通了。那怎么办呢?其实这个类就不是这么用的,他仅仅是需要获取一个Class对象就可以了,那还不容易啊-- 取所有类的父类Object,用Object.class难道不比你的用你正在写类自身方便安全吗 ?呵呵,下面给出一个例子,以方便交流。 import java.util.Properties; import java.io.InputStream; import java.io.IOException;/** * 读取Properties文件的例子 * File: TestProperties.java * User: leimin * Date: 2008-2-15 18:38:40 */ public final class TestProperties {private static String param1;private static String param2;static {Properties prop = new Properties();InputStream in = Object. class .getResourceAsStream( "/test.properties" );try {prop.load(in);param1 = prop.getProperty( "initYears1" ).trim();param2 = prop.getProperty( "initYears2" ).trim();} catch (IOException e) {e.printStackTrace();}}/*** 私有构造方法,不需要创建对象*/private TestProperties() {}public static String getParam1() {return param1;}public static String getParam2() {return param2;}public static void main(String args[]){System.out.println(getParam1());System.out.println(getParam2());} } 运行结果:151 152 当然,把Object.class换成int.class照样行,呵呵,大家可以试试。另外,如果是static方法或块中读取Properties文件,还有一种最保险的方法,就是这个类的本身名字来直接获取Class对象,比如本例中可写成TestProperties.class,这样做是最保险的方法2 获取路径的方式:File fileB = new File( this .getClass().getResource( "" ).getPath());System. out .println( "fileB path: " + fileB); 2.2获取当前类所在的工程名:System. out .println("user.dir path: " + System. getProperty ("user.dir"))<span style="background-color: white;">3 获取路径的一个简单的Java实现</span> /**

❹ JAVA中如何读取src下所有的properties文件

最常用读取properties文件的方法InputStream in = getClass().getResourceAsStream("资源Name");这种方式要求properties文件和当前类在同一文件夹下面。如果在不同的包中,必须使用:InputStream ins = this.getClass().getResourceAsStream("/cn/zhao/properties/testPropertiesPath2.properties");Java中获取路径方法获取路径的一个简单实现反射方式获取properties文件的三种方式1 反射方式获取properties文件最常用方法以及思考:Java读取properties文件的方法比较多,网上最多的文章是"Java读取properties文件的六种方法",但在Java应用中,最常用还是通过java.lang.Class类的getResourceAsStream(String name) 方法来实现,但众多读取properties文件的代码中,都会这么做:InputStream in = getClass().getResourceAsStream("资源Name");这里面有个问题,就是getClass()调用的时候默认省略了this,this是不能在static(静态)方法或者static块中使用的,原因是static类型的方法或者代码块是属于类本身的,不属于某个对象,而this本身就代表当前对象,而静态方法或者块调用的时候是不用初始化对象的。问题是:假如不想让某个类有对象,那么会将此类的默认构造方法设为私有,当然也不会写别的共有的构造方法。并且我这个类是工具类,都是静态的方法和变量,要在静态块或者静态方法中获取properties文件,这个方法就行不通了。其实这个类就不是这么用的,他仅仅是需要获取一个Class对象就可以了,那就容易了,取所有类的父类Object,用Object.class比用正在写类自身方便安全,下面给出一个例子,以方便交流。 import java.util.Properties; import java.io.InputStream; import java.io.IOException; /** * 读取Properties文件的例子 * File: TestProperties.java * User: leimin * Date: 2008-2-15 18:38:40 */ public final class TestProperties { private static String param1; private static String param2; static { Properties prop = new Properties(); InputStream in = Object. class .getResourceAsStream( "/test.properties" ); try { prop.load(in); param1 = prop.getProperty( "initYears1" ).trim(); param2 = prop.getProperty( "initYears2" ).trim(); } catch (IOException e) { e.printStackTrace(); } } /** * 私有构造方法,不需要创建对象 */ private TestProperties() { } public static String getParam1() { return param1; } public static String getParam2() { return param2; } public static void main(String args[]){ System.out.println(getParam1()); System.out.println(getParam2()); } } 运行结果: 151 152 当然,把Object.class换成int.class也行。另外,如果是static方法或块中读取Properties文件,还有一种最保险的方法,就是这个类的本身名字来直接获取Class对象,比如本例中可写成TestProperties.class,这样做是最保险的方法。2 获取路径的方式:File fileB = new File( this .getClass().getResource( "" ).getPath()); System. out .println( "fileB path: " + fileB); 2.2获取当前类所在的工程名:System. out .println("user.dir path: " + System. getProperty ("user.dir"))<span style="background-color: white;">3 获取路径的一个简单的Java实现</span> /** *获取项目的相对路径下文件的绝对路径 * * @param parentDir *目标文件的父目录,例如说,工程的目录下,有lib与bin和conf目录,那么程序运行于lib or * bin,那么需要的配置文件却是conf里面,则需要找到该配置文件的绝对路径 * @param fileName *文件名 * @return一个绝对路径 */ public static String getPath(String parentDir, String fileName) { String path = null; String userdir = System.getProperty("user.dir"); String userdirName = new File(userdir).getName(); if (userdirName.equalsIgnoreCase("lib") || userdirName.equalsIgnoreCase("bin")) { File newf = new File(userdir); File newp = new File(newf.getParent()); if (fileName.trim().equals("")) { path = newp.getPath() + File.separator + parentDir; } else { path = newp.getPath() + File.separator + parentDir + File.separator + fileName; } } else { if (fileName.trim().equals("")) { path = userdir + File.separator + parentDir; } else { path = userdir + File.separator + parentDir + File.separator + fileName; } } return path; } 4 利用反射的方式获取路径:InputStream ips1 = Enumeration . class .getClassLoader() .getResourceAsStream( "cn/zhao/enumStudy/testPropertiesPath1.properties" ); InputStream ips2 = Enumeration . class .getResourceAsStream( "testPropertiesPath1.properties" ); InputStream ips3 = Enumeration . class .getResourceAsStream( "properties/testPropertiesPath2.properties" );

❺ 如何读取.properties文件配置的两种方法

[html] view plain print?import java.io.IOException;  import java.io.InputStream;  import java.io.InputStreamReader;  import java.util.Properties;    import org.slf4j.Logger;  import org.slf4j.LoggerFactory;  import org.springframework.core.io.DefaultResourceLoader;  import org.springframework.core.io.Resource;  import org.springframework.core.io.ResourceLoader;  import org.springframework.util.DefaultPropertiesPersister;  import org.springframework.util.PropertiesPersister;    /**   * Properties Util函数.   *    * @author uniz   */  public class PropertiesUtils {        private static final String DEFAULT_ENCODING = "UTF-8";        private static Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);        private static PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();      private static ResourceLoader resourceLoader = new DefaultResourceLoader();        /**       * 载入多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的载入.       * 文件路径使用Spring Resource格式, 文件编码使用UTF-8.       *        * @see org.springframework.beans.factory.config.PropertyPlaceholderConfigurer       */      public static Properties loadProperties(String… resourcesPaths) throws IOException {          Properties props = new Properties();            for (String location : resourcesPaths) {                logger.debug("Loading properties file from:" + location);                InputStream is = null;              try {                  Resource resource = resourceLoader.getResource(location);                  is = resource.getInputStream();                  propertiesPersister.load(props, new InputStreamReader(is, DEFAULT_ENCODING));              } catch (IOException ex) {                  logger.info("Could not load properties from classpath:" + location + ": " + ex.getMessage());              } finally {                  if (is != null) {                      is.close();                  }              }          }          return props;      }            public static String getDataVal(String key) {          try {              Properties properties = PropertiesUtils.loadProperties("/config/config.properties");              if (properties == null) return "";                        return new String((properties.getProperty(key))                      .getBytes("ISO8859_1"), "utf-8");          } catch (Exception e) {              e.printStackTrace();              return null;          }      }  }  [html] view plain print?   [html] view plain print?

❻ 如何在java类中读取Properties配置文件

最常用读取properties文件的方法 InputStream in = getClass().getResourceAsStream("资源Name");这种方式要求properties文件和当前类在同一文件夹下面。如果在不同的包中,必须使用: InputStream ins = this.getClass().getResourceAsStream(

❼ jar如何引用lib里的properties文件

读取jar包内配置文件_话阍谙钅恐惺褂_roperties配置文件的时候都将相关的properties文件放在src目录下,在将该app打包生成jar后,相应的properties配置文件生…?_话阍谙钅恐惺褂_roperties配置文件的时候都将相关的properties文件放在src目录下,在将该app打包生成jar后,相应的properties配置文件生成在jar包中,这样的话要修改配置文件又要重新打jar包,那是相当的麻烦。?_热徽饷绰榉常憧隙ㄏ虢渲梦募旁谄渌哪柯枷拢傻_ar包内不包含相应的配置文件,修改配置文件无需重新打包,没错,下面就是一种解决方案了。?_寥jar包内配置文件:?_nputStream in = this.getClass().getClassLoader().getResourceAsStream(“/configfilename.properties”);?_寥jar包外配置文件:?_tring filePath = System.getProperty(“user.dir”) + “/conf/configfilename.properties”;?_nputStream in = new BufferedInputStream(new FileInputStream(filePath));?_硗猓绻_pp中使用到log4j.properties文件,默认的存放路径是src/log4j.properties,同上面一样,我想把log4j.properties放在其他目录中,这样一来,在修改log4j配置文件的时候无需重新打jar包。?__ain函数第一行添加如下代码:?_ropertyConfigurator.configure(System.getProperty(“user.dir”) + “/conf/log4j.properties”);

❽ web.xml中如何读取properties配置文件中的值

方法如下:

<context-param>

<param-name>log4jConfigLocation</param-name>

<param-value>classpath:/config/log4j.properties</param-value>

</context-param>

❾ 请教c3p0连接池如何读Properties配置文件

<!– 读取Properties配置文件路径 –><bean id="propertyConfig" class="org.springframework.beans.factory.config."><property name="location" value="classpath:jdbc.properties"></property></bean><!– 数据源配置 –><!–<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">>–><!– 设置JDBC驱动名称 –><!–<property name="driverClass" value="${jdbc.driver}" />>–><!– 设置JDBC连接URL –><!–<property name="jdbcUrl" value="${jdbc.url}" />>–><!– 设置数据库用户名 –><!–<property name="user" value="${jdbc.username}" />>–><!– 设置数据库密码 –><!–<property name="password" value="${jdbc.password}" />>–><!– 设置连接池初始值 –><!–<property name="initialPoolSize" value="${jdbc.initialPoolSize}" />>–><!– 设置连接池最小空闲值 –><!–<property name="minPoolSize" value="${jdbc.minPoolSize}" />>–><!– 设置连接池最大值 –><!–<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />>–><!–最大空闲时间,20分钟内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 –><!–<property name="maxIdleTime" value="1200" />>–><!–<property name="acquireIncrement" value="2" />–><!–<property name="idleConnectionTestPeriod" value="60" />–><!–获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。Default: false–><!–<property name="breakAfterAcquireFailure">–><!–<value>false</value>–><!–</property>–><!–</bean>–>

未经允许不得转载:山九号 » 读取properties配置文件|如何在spring中读取properties配置文件里面的信息

赞 (0)