1.Java中的properties配置文件怎么写,代码
public static void main(String[] args) {
Properties p = new Properties();
p.setProperty("id", "user1");
p.setProperty("password", "123456");
try{
PrintStream stm = new PrintStream(new File("e:\test.properties"));
p.list(stm);
} catch (IOException e) {
e.printStackTrace();
}
}
2.properties文件怎么写
InputStream in = 类名.class.getClassLoader().getResourceAsStream("propertes名字.properties");
Properties prop = new Properties();
prop.load(in)
oracleDb_Driver = prop.getProperty("oracleDb_Driver-properties里面的字段");
3.java的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: leizhimin * 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"))3 获取路径的一个简单的Java实现 /** *获取项目的相对路径下文件的绝对路径 * * @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" );。
4.Java中的properties配置文件怎么写,代码
public static void main(String[] args) { Properties p = new Properties(); p.setProperty("id", "user1"); p.setProperty("password", "123456"); try{ PrintStream stm = new PrintStream(new File("e:\test.properties")); p.list(stm); } catch (IOException e) { e.printStackTrace(); }}。
5.如何写一个.properties文件,如何调用
properties属性文件内容都是以键值对形式存在的,比如我写一个叫test.properties的文件,打开后可以再里面写如:name=Tom
而在java类中需要new一个Properties类的对象,如下:
Properties properties = new Properties();
接下来需要获取test.properties的文件路径:
String path = Thread.currentThread().getContextClassLoader().getResource("test.properties").getPath();
然后加载该文件:
properties.load(new FileInputStream(path));
最后你就可以get它的属性了:
String name_1=properties.getProperty("name");
这个name_1的值就是“TOM”了。
(因为涉及到文件流,所以加载那一步需要try catch,根据编译器提示自己加吧)
6.JAVa读取配置文件位置ReaderProperties类要怎么写
package com; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties;/*** 读取配置文件properties文件*/ public class Configuration { private Properties pro; private FileInputStream inputFile; private FileOutputStream outputFile; public Configuration(){ pro = new Properties(); } /** * 初始化Configuration类 * @param filePath 要读取的配置文件的路径+名称 */ public Configuration(String filePath){ pro = new Properties(); try { //读取属性文件 inputFile = new FileInputStream(filePath); //装载文件 pro.load(inputFile); inputFile.close(); } catch (FileNotFoundException e) { System.out.println("读取属性文件--->失败!- 原因:文件路径错误或者文件不存在"); e.printStackTrace(); } catch (IOException e) { System.out.println("装载文件--->失败!"); e.printStackTrace(); } } /** * 得到key值 * @param key 取得其值的键 * @return 取得键值 */ public String getValue(String key){ if(pro.containsKey(key)){ String value = pro.getProperty(key); return value; }else{ return ""; } } /** * 得到key值 * @param filePath properties文件的路径+文件名 * @param key 取得其值的键 * @return 取得键值 */ public String getValue(String filePath, String key){ try { String value = ""; inputFile = new FileInputStream(filePath); pro.load(inputFile); inputFile.close(); if(pro.contains(key)){ value = pro.getProperty(key); return value; }else{ return ""; } } catch (FileNotFoundException e) { e.printStackTrace(); return ""; } catch (IOException e) { e.printStackTrace(); return ""; } catch (Exception e) { e.printStackTrace(); return ""; } } /** * 清除properties文件中所有的key和其值 */ public void clear(){ pro.clear(); } /** * 改变或添加一个key的值 * 当key存在于properties文件中时该key的值被value所代替, * 当key不存在时,该key的值是value * @param key 要存入的键 * @param value 要存入的值 */ public void setValue(String key, String value){ pro.setProperty(key, value); } /** * 将更改后的文件数据存入指定的文件中,该文件可以事先不存在 * @param fileName 文件路径+文件名称 * @param description 对该文件的描述 */ public void saveFile(String fileName, String description){ try { outputFile = new FileOutputStream(fileName); pro.store(outputFile, description); outputFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ioe){ ioe.printStackTrace(); } } /** * 测试方法 * @param args */ public static void main(String[] args) { Configuration conf = new Configuration(".\\.\\WebContent\\WEB-INF\\jdbc.properties"); String value = conf.getValue("hibernate.dialect"); System.out.println(value); } }。
7.springboot application.properties 写多个配置文件怎么写
springboot application.properties 写多个配置文件的方法:# 文件编码 banner.charset= UTF-8# 文件位置 banner.location= classpath:banner.txt# 日志配置# 日志配置文件的位置。
例如对于Logback的`classpath:logback.xml` logging.config= # %wEx#记录异常时使用的转换字。logging.exception-conversion-word= # 日志文件名。
例如`myapp.log` logging.file= # 日志级别严重性映射。 例如`logging.level.org.springframework = DEBUG` logging.level.*= # 日志文件的位置。
例如`/ var / log logging.path= # 用于输出到控制台的Appender模式。 只支持默认的logback设置。
logging.pattern.console=# 用于输出到文件的Appender模式。 只支持默认的logback设置。
logging.pattern.file= # 日志级别的Appender模式(默认%5p)。 只支持默认的logback设置。
logging.pattern.level=#注册日志记录系统的初始化挂钩。logging.register-shutdown-hook= false# AOP 切面# 添加@。
spring.aop.auto= true# 是否要创建基于子类(CGLIB)的代理(true),而不是基于标准的基于Java接口的代理(false)。spring.aop.proxy-target-class= false# 应用程序上下文初始化器# 应用指标。
spring.application.index= # 应用程序名称。spring.application.name= # 国际化(消息源自动配置)# spring.messages.basename= messages# 以逗号分隔的基础名称列表,每个都在ResourceBundle约定之后。
# 加载的资源束文件缓存到期,以秒为单位。 设置为-1时,软件包将永久缓存。
spring.messages.cache-seconds= -1# 消息编码。spring.messages.encoding= UTF-8# 设置是否返回到系统区域设置,如果没有找到特定语言环境的文件。
spring.messages.fallback-to-system-locale= true# REDIS (Redis 配置)# 连接工厂使用的数据库索引。spring.redis.database= 0# Redis服务器主机。
spring.redis.host= localhost# 登录redis服务器的密码。spring.redis.password= # 给定时间池可以分配的最大连接数。
使用负值为无限制。spring.redis.pool.max-active= 8# 池中“空闲”连接的最大数量。
使用负值来表示无限数量的空闲连接。spring.redis.pool.max-idle= 8# 连接分配在池耗尽之前在抛出异常之前应阻止的最大时间量(以毫秒为单位)。
使用负值无限期地阻止。spring.redis.pool.max-wait= -1# 定义池中维护的最小空闲连接数。
此设置只有在正值时才有效果。spring.redis.pool.min-idle= 0# redis服务器端口 spring.redis.port= 6379# redis服务器名称 spring.redis.sentinel.master=# spring.redis.sentinel.nodes= # 连接超时(毫秒)。
spring.redis.timeout= 0# 管理员 (Spring应用程序管理员JMX自动配置)# 开启应用管理功能。spring.application.admin.enabled= false# JMX应用程序名称MBean。
spring.application.admin.jmx-name= org.springframework.boot:type= Admin,name= SpringApplication# 自动配置# 自动配置类排除。spring.autoconfigure.exclude= # spring 核心配置# 跳过搜索BeanInfo类。
spring.beaninfo.ignore= true# spring 缓存配置# 由底层缓存管理器支持的要创建的缓存名称的逗号分隔列表。spring.cache.cache-names= # 用于初始化EhCache的配置文件的位置。
spring.cache.ehcache.config= # 用于创建缓存的规范。 检查CacheBuilderSpec有关规格格式的更多细节。
spring.cache.guava.spec= # 用于初始化Hazelcast的配置文件的位置。spring.cache.hazelcast.config= # 用于初始化Infinispan的配置文件的位置。
spring.cache.infinispan.config= # 用于初始化缓存管理器的配置文件的位置。spring.cache.jcache.config= # 用于检索符合JSR-107的缓存管理器的CachingProvider实现的完全限定名称。
只有在类路径上有多个JSR-107实现可用时才需要。spring.cache.jcache.provider= # 缓存类型,默认情况下根据环境自动检测。
spring.cache.type= # spring配置 (配置文件应用侦听器)# 配置文件位置。spring.config.location= # 配置文件名。
spring.config.name= application Springboot的多配置文件是指:系统中存在多个配置文件,在不同的运行环境使用不同的配置文件即可。启动项目的方法一般有两种 :1、运行RootApplication中的main方法。
2、使用命令:mvn spring-boot:run 这两方法默认都是使用application.properties中的配置信息,如果有指spring.profiles.active则使用指定的配置信息,这种方式一般用在产品运行时,在开发和测试的时候则需要指定配置文件。
8.如何读取.properties文件配置的两种方法
[html] view plain copy 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.; 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 (); private static ResourceLoader resourceLoader = new DefaultResourceLoader(); /** * 载入多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的载入. * 文件路径使用Spring Resource格式, 文件编码使用UTF-8. * * @see org.springframework.beans.factory.config. */ 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 copy print?[html] view plain copy print?。
9.properties文件怎么写
InputStream in = 类名.class.getClassLoader().getResourceAsStream("propertes名字.properties");
Properties prop = new Properties();
prop.load(in)
oracleDb_Driver = prop.getProperty("oracleDb_Driver-properties里面的字段");
转载请注明出处育才学习网 » properties配置文件怎么写