关于Object.class.getResourceAsStream方法读取文件的使用

本文介绍如何在Java中通过相对路径正确加载配置文件,并解决了在项目中找不到配置文件的问题。

先附上代码。

package com.property;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;


public class Test {
	
	
	public static int getSocketPort(String tomcatpath, String propertyName) {

        Properties prop = new Properties();
        InputStream in = null;
        String socketPort = null;

        try {

            // 加载tomcatpath.properties文件
            in = Object.class.getResourceAsStream(tomcatpath);
            prop.load(in);

            Enumeration it = prop.propertyNames();
            while (it.hasMoreElements()) {
                String key = (String) it.nextElement();

                if (propertyName.equals(key)) {
                    socketPort = prop.getProperty(key);
                    break;
                }
            }

        } catch (FileNotFoundException e1) {

            throw new RuntimeException(e1);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
            throw new RuntimeException(e);

        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return Integer.parseInt(socketPort);
    }
}

package com.property;

public class Main {

	public static void main(String[] args) {
		int socketPort = Test.getSocketPort("/test/tomcatpath.properties", "tomcat_port");
		System.out.println(socketPort);
	}

}

在使用Object.class.getResourceAsStream方法时,在src同级目录下创建文件夹configss,文件夹下创建log4j.properties文件和文件夹test,test文件夹下创建文件tomcatpath.properties,如图


此时,执行main函数,程序会直接报错,经过研究,找出问题如下:

需要将configss文件夹执行build path--use as source folder,结果如下图


此时,执行main函数,方法会成功,输出tomcat_port的值。

原因:当将configss文件夹执行build path--use as source folder时,configss文件夹下的配置文件可以被类以相对路径直接读写。(与configss文件夹本身名称无关)

### 如何在Spring Boot中读取application.yml文件的配置内容 #### 方法一:通过Environment对象读取 `Environment` 是 Spring 提供的一个接口,用于访问应用程序上下文中定义的所有属性。可以通过 `@Autowired` 将其注入到任何 Bean 中并调用相应的方法来获取配置项[^3]。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; public class ConfigReader { @Autowired private Environment environment; public String getProperty(String key) { return environment.getProperty(key); } } ``` #### 方法二:使用`@Value`注解读取单个配置项 如果只需要读取少量配置项,则可以使用 `@Value` 注解直接将配置值注入到字段中。 ```java import org.springframework.stereotype.Component; @Component public class SimpleConfig { @Value("${app.name}") private String appName; public String getAppName() { return appName; } } ``` #### 方法三:使用`@ConfigurationProperties`批量读取配置 当有多个相关的配置项时,推荐使用 `@ConfigurationProperties` 来一次性绑定整个配置结构到 Java 对象中[^4]。 1. 定义一个 POJO 类表示配置结构: ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "database") public class DatabaseConfig { private String url; private String username; private String password; // Getters and Setters public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } ``` 2. 配置文件示例 (`application.yml`): ```yaml database: url: jdbc:mysql://localhost:3306/testdb username: root password: secret ``` 3. 使用该配置类: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class DatabaseController { @Autowired private DatabaseConfig databaseConfig; @GetMapping("/config") public String getConfig() { return "Database URL: " + databaseConfig.getUrl(); } } ``` #### 方法四:使用`YamlPropertiesFactoryBean`手动加载 YAML 文件 对于更复杂的场景或者需要动态加载外部 YAML 文件的情况,可以直接使用 `YamlPropertiesFactoryBean` 手动解析 YAML 文件。 ```java import org.yaml.snakeyaml.Yaml; import java.io.InputStream; import java.util.Map; public class YamlLoader { public Map<String, Object> loadYaml(String fileName) throws Exception { InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); Yaml yaml = new Yaml(); return yaml.load(inputStream); } } ``` --- ### 注意事项 - 如果项目中有多个配置文件且存在相同的键名,默认会以 `application.yml` 的内容为准。 - 推荐为项目添加 `spring-boot-configuration-processor` 依赖,以便 IDE 能够提供自动补全功能[^4]。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值