文件读取

  • spring 读取配置文件

spring 注解  @PropertySource 引入文件   @Value读取文件内容,EmbeddedValueResolverAware读取文件内容   @Value注解:

1、基本数值;

2、可以写SpEL; #{};

3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)

@PropertySource 导入一个外部的配置文件,相当于xml中如下配置

<context:property-placeholder location="classpath:jdbc.properties"/>
  • 使用方式:

定义一个jdbc.properties文件

db.user=root
db.password=123456
db.driverClass=com.mysql.jdbc.Driver

定义配置类,引入jdbc文件

 @PropertySource

@PropertySource("classpath:/jdbc.properties")
@Configuration
public class MainConfigOfProfile2 implements EmbeddedValueResolverAware {
 
    @Value("${db.user}")
    private String user;
 
    @Value("张三")
    private String name;
    @Value("#{20-2}")
    private Integer age;
 
    private StringValueResolver valueResolver;
 
    private String driverClass;
 
    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.valueResolver = resolver;
        driverClass = valueResolver.resolveStringValue("${db.driverClass}");
    }
}
  • @ConfigurationProperties

该类加上 Component 和 ConfigurationProperties 注解,并在 ConfigurationProperties 注解中添加属性 prefix,作用可以区分同名配置

@Component
@ConfigurationProperties(prefix = "school")
public class ConfigInfo {

    private String name;
    private String websit;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getWebsit() {
        return websit;
    }

    public void setWebsit(String websit) {
        this.websit = websit;
    }
}

application.properties 配置文件

#设置内嵌 Tomcat 端口号
server.port=9090
#设置上下文根
server.servlet.context-path=/config
school.name=ssm
school.websit=http://www.baidu.com
  • Java 读取 .properties 配置文件的几种方式

1、基于ClassLoder读取配置文件注意:该方式只能读取类路径下的配置文件,有局限但是如果配置文件在类路径下比较方便。

  Properties properties = new Properties();
    // 使用ClassLoader加载properties配置文件生成对应的输入流
    InputStream in = PropertiesMain.class.getClassLoader().getResourceAsStream("config/config.properties");
    // 使用properties对象加载输入流
    properties.load(in);
    //获取key对应的value值
    properties.getProperty(String key);

 2、基于 InputStream 读取配置文件(注意:该方式的优点在于可以读取任意路径下的配置文件)

Properties properties = new Properties();
// 使用InPutStream流读取properties文件
BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/config.properties"));
properties.load(bufferedReader);
// 获取key对应的value值
properties.getProperty(String key);

3、这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可

ResourceBundle rb = ResourceBundle.getBundle("conf", Locale.getDefault());

Integer.parseInt(rb.getString("redis_maxTotal"));
Integer.parseInt(rb.getString("redis_maxIdle"));
Long.parseLong(rb.getString("redis_MaxWaitMillis"));
Boolean.getBoolean(rb.getString("redis_testOnBorrow"))

    从 InputStream 中读取,获取 InputStream 的方法和上面一样,不再赘述

ResourceBundle resource = new PropertyResourceBundle(inStream);

注意:在使用中遇到的最大的问题可能是配置文件的路径问题,如果配置文件入在当前类所在的包下,那么需要使用包名限定,如:config.properties入在com.test.config包下,则要使用com/test/config/config.properties(通过Properties来获取)或com/test/config/config(通过ResourceBundle来获取);属性文件在src根目录下,则直接使用config.properties或config即可。

application.properties文件内容如下

minio.endpoint=http://localhost:9000
minio.accessKey=minioadmin
minio.secretKey=minioadmin
minio.bucketName=demo

1. 从当前的类加载器的getResourcesAsStream来获取

/**
     * 1. 方式一
     * 从当前的类加载器的getResourcesAsStream来获取
     * InputStream inputStream = this.getClass().getResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        InputStream inputStream = this.getClass().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("jdbc.url");
        System.out.println("property = " + property);
    }

2. 从当前的类加载器的getClassLoader().getResourcesAsStream来获取

/**
     * 2. 方式二
     * 从当前的类加载器的getResourcesAsStream来获取
     * InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

3. 使用Class类的getSystemResourceAsStream静态方法 和使用当前类的ClassLoader是一样的

 /**
     * 3. 方式三
     * 使用Class类的getSystemResourceAsStream方法 和使用当前类的ClassLoader是一样的
     * InputStream inputStream = ClassLoader.getSystemResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test3() throws IOException {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

4. 使用Spring-core包中的ClassPathResource读取

    /**
     * 4. 方式四
     * Resource resource = new ClassPathResource(path)
     *
     * @throws IOException
     */
    @Test
    public void test4() throws IOException {
        Resource resource = new ClassPathResource("config/application.properties");
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

5. 从文件中读取,new BufferedInputStream(InputStream in)

/**
     * 5. 方式五
     * 从文件中获取,使用InputStream字节,主要是需要加上当前配置文件所在的项目src目录地址。路径配置需要精确到绝对地址级别
     * BufferedInputStream继承自InputStream
     * InputStream inputStream = new BufferedInputStream(new FileInputStream(name)
     * 这种方法读取需要完整的路径,优点是可以读取任意路径下的文件,缺点是不太灵活
     * @throws IOException
     */
    @Test
    public void test5() throws IOException {
        InputStream inputStream = new BufferedInputStream(new FileInputStream("src/main/resources/config/application.properties"));
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

6.从文件中读取,new FileInputStream(String name)

/**
     * 6. 方式六
     * 从文件中获取,使用InputStream字节,主要是需要加上当前配置文件所在的项目src目录地址。路径配置需要精确到绝对地址级别
     * FileInputStream继承自InputStream
     * InputStream inputStream = new FileInputStream(name)
     * 这种方法读取需要完整的路径,优点是可以读取任意路径下的文件,缺点是不太灵活
     * @throws IOException
     */
    @Test
    public void test6() throws IOException {
        InputStream inputStream = new FileInputStream("src/main/resources/config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

7. 使用PropertyResourceBundle读取InputStream流

 /**
     * 7. 方式七
     * 使用InputStream流来进行操作ResourceBundle,获取流的方式由以上几种。
     * ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
     * @throws IOException
     */
    @Test
    public void test7() throws IOException {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("config/application.properties");
        ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
        Enumeration<String> keys = resourceBundle.getKeys();
        while (keys.hasMoreElements()) {
            String s = keys.nextElement();
            System.out.println(s + " = " + resourceBundle.getString(s));
        }
    }

8. 使用ResourceBundle.getBundle读取

 /**
     * 8. 方式八
     * ResourceBundle.getBundle的路径访问和 Class.getClassLoader.getResourceAsStream类似,默认从根目录下读取,也可以读取resources目录下的文件
     * ResourceBundle rb = ResourceBundle.getBundle("b") //不需要指定文件名的后缀,只需要写文件名前缀即可
     */
    @Test
    public void test8(){
        //ResourceBundle rb = ResourceBundle.getBundle("jdbc"); //读取resources目录下的jdbc.properties
        ResourceBundle rb2 = ResourceBundle.getBundle("config/application");//读取resources/config目录下的application.properties
        for(String key : rb2.keySet()){
            String value = rb2.getString(key);
            System.out.println(key + ":" + value);
        }

    }
  • 第三方读取配置文件

commons-io 读取 配置文件
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency> 

实例(可读取任意文件下的内容,按行读取)

public class CityMapConfig {

    public static Map<String,String> CITY_MAP = new HashMap<String,String>();

    public static void init() {
        InputStream inputFile = Thread.currentThread().getContextClassLoader().getResourceAsStream("city.txt");
        try {
            List<String> list = IOUtils.readLines(inputFile);
            for(String str:list){
                String [] arr =str.split("	");
                CITY_MAP.put(arr[1],arr[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String args[]){
        init();
        System.out.println(JSON.toJSONString(CITY_MAP));
    }
}
  • commons-configuration pom 配置读取

        <dependency>
            <groupId>commons-configuration</groupId>
            <artifactId>commons-configuration</artifactId>
            <version>1.6</version>
        </dependency>
package com.zxwa.ntmss.process.config;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;


public class MysqlConfig {
    private static String CONFIG_PATH = "conf.properties";
    public static String DRIVER_CLASS = null;
    public static String URL = null;
    public static String USERNAME = null;
    public static String PASSWD = null;

    public static String URL_BUSINESS = null;
    public static String USERNAME_BUSINESS= null;
    public static String PASSWD_BUSINESS = null;

    private static PropertiesConfiguration config;
    static {
        init();
    }
    
    public static void init() {
        try {
            config = new PropertiesConfiguration(CONFIG_PATH);
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        DRIVER_CLASS=config.getString("drivername");
        URL=config.getString("url");
        USERNAME=config.getString("username");
        PASSWD=config.getString("password");

        URL_BUSINESS=config.getString("url.business");
        USERNAME_BUSINESS=config.getString("username.business");
        PASSWD_BUSINESS=config.getString("password.business");
    }
}

 任意位置文件读取

 String CONFIG = System.getProperty("user.dir").replaceAll("\\", "/") + "/conf/config.properties";
 String SCHEMA = System.getProperty("user.dir").replaceAll("\\", "/") + "/conf/indexSchema.xml";
  • hutool 读取 配置文件

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.3.2</version>
</dependency>
实例(可读取任意文件下的内容,按行读取)
  public static List<OcrModel> init() {
        List<OcrModel> ocrModels = new ArrayList<>();
        InputStream inputFile = Thread.currentThread().getContextClassLoader().getResourceAsStream("name.txt");
        try {
            List<String> list = IoUtil.readLines(inputFile, Charset.forName("UTF-8"), new ArrayList<>());
            for (String str : list) {
                OcrModel ocrConfig = new OcrModel();
                List<String> split = StrSpliter.split(str, " ", true, true);
                ocrConfig.setAppId(split.get(0));
                ocrConfig.setApiKey(split.get(1));
                ocrConfig.setSecretKey(split.get(2));
                ocrModels.add(ocrConfig);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ocrModels;
    }

 ClassPath资源访问-ClassPathResource

在Java编码过程中,我们常常希望读取项目内的配置文件,按照Maven的习惯,这些文件一般放在项目的src/main/resources下,读取的时候使用:

String path = "config.properties";
InputStream in = this.class.getResource(path).openStream();

  使用当前类来获得资源其实就是使用当前类的类加载器获取资源,最后openStream()方法获取输入流来读取文件流。

  面对这种复杂的读取操作,我们封装了ClassPathResource类来简化这种资源的读取:

ClassPathResource resource = new ClassPathResource("test.properties");
Properties properties = new Properties();
properties.load(resource.getStream());

Console.log("Properties: {}", properties);
  Props (Properties的第二个问题是读取非常不方便,需要我们自己写长长的代码进行load操作:)
properties = new Properties();
try {
    Class clazz = Demo1.class;
    InputStream inputestream = clazz.getResourceAsStream("db.properties");
    properties.load( inputestream);
}catch (IOException e) {
    //ignore
}

  而Props则大大简化为:

Props props = new Props("db.properties");
  使用
Props props = new Props("test.properties");
String user = props.getProperty("user");
String driver = props.getStr("driver");
故乡明
原文地址:https://www.cnblogs.com/luweiweicode/p/14148327.html