java读取Properties文件的方法
resource.properties的内容:
com.tsinkai.ettp.name=imooc com.tsinkai.ettp.website=www.imooc.com com.tsinkai.ettp.language=java
1、使用java.util.Properties的load(InputStream inStream)方法。
先读取文件生成inputStream流,再用load加载。
@Test public void testReadProperties3() throws IOException { Properties properties = new Properties(); // InputStream inputStream = this.getClass().getResourceAsStream("/resource.properties"); // InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("resource.properties"); Resource resource = new ClassPathResource("resource.properties"); InputStream inputStream = resource.getInputStream(); properties.load(inputStream); System.out.println(properties.getProperty("com.tsinkai.ettp.name")); }
2、使用org.springframework.core.io.support.PropertiesLoaderUtils;
@Test public void testReadProperties() throws IOException { Properties properties = PropertiesLoaderUtils.loadAllProperties("resource.properties"); String name = properties.getProperty("com.tsinkai.ettp.name"); System.out.println(name); }
3、使用java.util.ResourceBundle;
@Test public void testReadProperties2() throws IOException { ResourceBundle resourceBundle = ResourceBundle.getBundle("resource"); String name = resourceBundle.getString("com.tsinkai.ettp.name"); System.out.println(name); }
4、使用spring注解创建资源类
资源类:
package com.imooc.pojo; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @ConfigurationProperties(prefix="com.imooc.opensource")//属性前缀 @PropertySource(value="classpath:resource.properties")//文件路径 public class Resource { private String name; private String website; private String language; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } }
调用:
package com.tsinkai.ettp; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.tsinkai.ettp.common.Resource; @RunWith(SpringRunner.class) @SpringBootTest public class EttpCustomApplicationTests { @Autowired Resource customResource; @Test public void readResource() { Resource bean = new Resource(); BeanUtils.copyProperties(customResource, bean); System.out.println(bean.getName()); } }
就算这个世道烂成一堆粪坑,那也不是你吃屎的理由