To read properties files in Java, both in XML and text formats, you can use the java.util.Properties class.
Here's an example that demonstrates how to read properties files in both formats: XML Properties File Example: Assume you have an XML properties file named config.xml with the following content:
jdbc:mysql://localhost:3306/mydb
admin
password123
To read this XML properties file in Java, you can use the Properties class and an XML parser:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class XMLPropertiesExample {
public static void main(String[] args) {
Properties properties = new Properties();
try {
FileInputStream fileInputStream = new FileInputStream("config.xml");
properties.loadFromXML(fileInputStream);
} catch (IOException e) {
e.printStackTrace();
}
String databaseUrl = properties.getProperty("database.url");
String databaseUsername = properties.getProperty("database.username");
String databasePassword = properties.getProperty("database.password");
System.out.println("Database URL: " + databaseUrl);
System.out.println("Database Username: " + databaseUsername);
System.out.println("Database Password: " + databasePassword);
}
}
In this example, we create an instance of Properties and load the XML properties file using properties.loadFromXML(), passing a FileInputStream of the XML file.
The properties are then accessed using properties.getProperty() with the corresponding keys. Text Properties File Example: Assume you have a text-based properties file named config.properties with the following content:
database.url=jdbc:mysql://localhost:3306/mydb
database.username=admin
database.password=password123
To read this text properties file in Java, you can use the Properties class:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class TextPropertiesExample {
public static void main(String[] args) {
Properties properties = new Properties();
try {
FileInputStream fileInputStream = new FileInputStream("config.properties");
properties.load(fileInputStream);
} catch (IOException e) {
e.printStackTrace();
}
String databaseUrl = properties.getProperty("database.url");
String databaseUsername = properties.getProperty("database.username");
String databasePassword = properties.getProperty("database.password");
System.out.println("Database URL: " + databaseUrl);
System.out.println("Database Username: " + databaseUsername);
System.out.println("Database Password: " + databasePassword);
}
}
In this example, we load the text properties file using properties.load(), passing a FileInputStream of the properties file. The properties are then accessed using properties.getProperty() with the corresponding keys.
Both examples demonstrate how to read properties files in Java, whether in XML or text format, using the java.util.Properties class.