Java 如何从.properties文件中读取字符串

Java 如何从.properties文件中读取字符串,java,spring,Java,Spring,我需要一些配置文件。所以我在参考资料中创建了一个config.properties。这是最好的方法吗?它看起来很重。但可能比访问数据库要好 Properties properties = new Properties(); try { File file = ResourceUtils.getFile("classpath:config.properties"); InputStream in = new FileInputStream(file); properti

我需要一些配置文件。所以我在参考资料中创建了一个config.properties。这是最好的方法吗?它看起来很重。但可能比访问数据库要好

Properties properties = new Properties();

try 
{
    File file = ResourceUtils.getFile("classpath:config.properties");
    InputStream in = new FileInputStream(file);
    properties.load(in);
    String maxHolidays = (String) properties.get("maxHolidays");
    properties.setProperty("maxHolidays", "20");
}
catch(Exception e)
{
    System.out.println("");
}

如果我想为我的属性“maxHolidays”设置一个新值,是否也可以从代码中使用属性和读取值:

@Configuration
@PropertySource("classpath:config.properties")
public class ExampleConfig {

    @Value("${maxHolidays}")
    private String maxHolidays;

    public String getMaxHolidays() {
        return maxHolidays;
    }
}
然后,您可以
@Autowire
将该配置导入任何组件,并读取
maxHolidays
的值

if I want to set a new value to my property "maxHolidays" is it also possible from code 
如果更改是暂时的,也可以添加setter


如果您打算将更改保留回属性,则不能再将它们用作类路径资源(因为此资源通常会捆绑到您的JAR中),而是需要基于文件的属性-在这种情况下,使用,它提供了加载和存储方法。

注意,您的代码假设这是磁盘上的文件。有更简单的方法可以获取这些值,例如查看
@Value
。我只是将文件放在resources文件夹中。当我让它在服务器上以实时模式运行时,不应该给出错误。这是否回答了您的问题?如果我使用getFile(“classpath:config.properties”)类路径获取文件,那么如果我不使用IDE,而只是使用纯虚拟机,这可能会是一个问题。我是否向vm提供此参数?我应该将ExampleConfig类放在哪里?是的,我想保留该值。它应该保存在.properties文件中。啊好的。如果我想持久化它,我不能像在代码中那样使用路径,而是必须使用src/main/resources/config.properties,而不是classpath: