Two Ways to Read Java Properties Files: ClassLoader vs ResourceBundle
This tutorial shows two standard Java approaches for loading a jdbc.properties file: using ClassLoader.getResourceAsStream with Properties, and using ResourceBundle.getBundle, each with complete code examples and output verification.
Reading Java Properties Files: Two Approaches
This article demonstrates two standard ways to load configuration from a jdbc.properties file in a Java application.
Method 1: Using ClassLoader and Properties
The example uses a jdbc.properties file placed in the classpath root with the following content:
jdbc.driver= com.mysql.jdbc.cj,Driver
jdbc.url=jdbc:mysql://localhost:3306/music
jdbc.username=root
jdbc.password=123The directory structure shows the properties file alongside the Java source.
In a test class testDemo, the file is loaded via the context class loader:
InputStream is = testDemo.class.getClassLoader.getResourceAsStream("jdbc.properties");
Properties pro = new Properties();
pro.load(is);
String driver = pro.getProperty("jdbc.driver");
String url = pro.getProperty("jdbc.url");
System.out.println(driver + url);The output screenshot confirms the driver class name and JDBC URL are printed correctly.
Method 2: Using ResourceBundle
The ResourceBundle API provides a simpler alternative for properties files named without the .properties extension:
ResourceBundle rb = ResourceBundle.getBundle("jdbc"); // reads jdbc.properties
String name = rb.getString("jdbc.driver"); // retrieves value for key jdbc.driver
System.out.println(name);The output screenshot shows the driver class name printed.
Both approaches are part of the Java standard library and require no external dependencies.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
