How to load configuration files in Java?
There are several methods typically used for loading configuration files in Java:
- Characteristics
- Characteristics
- import the data
- Retrieve the property.
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigLoader {
public static void main(String[] args) {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("config.properties"));
String value = properties.getProperty("key");
System.out.println("Value: " + value);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Loader of Classes
- Loader of classes
- obtain the stream of resources
- Characteristics
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigLoader {
public static void main(String[] args) {
Properties properties = new Properties();
try (InputStream inputStream = ConfigLoader.class.getClassLoader().getResourceAsStream("config.properties")) {
properties.load(inputStream);
String value = properties.getProperty("key");
System.out.println("Value: " + value);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- A collection of resources.
- collection of resources
- .property files
import java.util.ResourceBundle;
public class ConfigLoader {
public static void main(String[] args) {
ResourceBundle resourceBundle = ResourceBundle.getBundle("config");
String value = resourceBundle.getString("key");
System.out.println("Value: " + value);
}
}
The configuration file, named config.properties in the example, needs to be placed in the classpath or the absolute path specified, regardless of the method used. It can be modified as needed.