How to use Java property files?

后端 未结 17 1158
时光取名叫无心
时光取名叫无心 2020-11-22 11:13

I have a list of key/value pairs of configuration values I want to store as Java property files, and later load and iterate through.

Questions:

  • Do I ne
17条回答
  •  情歌与酒
    2020-11-22 11:55

    By default, Java opens it in the working directory of your application (this behavior actually depends on the OS used). To load a file, do:

    Properties props = new java.util.Properties();
    FileInputStream fis new FileInputStream("myfile.txt");
    props.load(fis)
    

    As such, any file extension can be used for property file. Additionally, the file can also be stored anywhere, as long as you can use a FileInputStream.

    On a related note if you use a modern framework, the framework may provide additionnal ways of opening a property file. For example, Spring provide a ClassPathResource to load a property file using a package name from inside a JAR file.

    As for iterating through the properties, once the properties are loaded they are stored in the java.util.Properties object, which offer the propertyNames() method.

提交回复
热议问题