JAVA普通类如何加载properties配置文件

如图Test类加载config.properties配置文件,且保证打包后也能正常读取

import java.io.InputStream;
import java.util.Properties;

public class Test {
    public static void main(String[] args) {
        //1.读取配置文件
        Properties properties = new Properties();
        try {
            InputStream inputStream = Test.class.getResourceAsStream("/config.properties");
            // 如果配置文件在项目的根目录下
            // input = new FileInputStream("config.properties");
            properties.load(inputStream);
            System.out.println("配置文件已成功添加!");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("无法添加配置文件:" + e.getMessage());
        }
        System.out.println("配置文件内容为:" + properties.getProperty("file.path"));
    }
}

如果在resource目录下,则地址换成/resource/config,properties

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中,可以使用以下方式读取配置的信息: 1. 使用Properties PropertiesJava中专门用于读取配置文件。可以使用load()方法加载配置文件,使用getProperty()方法获取配置文件中的属性值。 例如,假设有一个配置文件config.properties,其中包含了一个属性名称为“username”,属性值为“admin”,则可以使用以下代码读取配置文件中的属性值: ```java import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class ConfigReader { public static void main(String[] args) throws IOException { Properties prop = new Properties(); FileInputStream input = new FileInputStream("config.properties"); prop.load(input); String username = prop.getProperty("username"); System.out.println(username); } } ``` 2. 使用YAML文件 YAML是一种简单易读的数据格式,可以用于存储配置信息。可以使用Jackson库将YAML文件转换成Java对象,然后直接访问Java对象的属性值。 例如,假设有一个配置文件config.yaml,其中包含了一个属性名称为“username”,属性值为“admin”,则可以使用以下代码读取配置文件中的属性值: ```java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import java.io.File; import java.io.IOException; public class ConfigReader { public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); Config config = mapper.readValue(new File("config.yaml"), Config.class); String username = config.getUsername(); System.out.println(username); } } class Config { private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } ``` 其中,Config是一个普通Java,包含了一个属性username和相应的getter和setter方法。使用Jackson库的readValue()方法将YAML文件转换成Config对象,然后可以直接访问Config对象的属性值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值