Skip to main content

Reading properties from a file with example

Essential Java File and Configuration Management: Properties, Directories, and Date Logic

Java Properties File Workflow Java Properties File Workflow 1 Externalize Config Store configuration variables in a .properties file. 2 Resource Placement Place property files inside the src/main/resources directory. 3 Define Properties Add key-value pairs like comma-separated role IDs. 4 Load via ClassLoader Read and parse properties at runtime using Java I/O APIs.
Figure: Java Properties File Workflow

Handling configuration data and interacting with the local file system are fundamental requirements for backend developers. Hardcoding configuration values such as database connection strings, feature toggles, or authorization role IDs inside source code leads to rigid, unmaintainable applications that require recompilation for every environment change. Externalizing these parameters into standard Java .properties files keeps applications modular and configurable.

Pick a language, then press Listen.

Beyond configuration management, enterprise systems frequently require programmatic file system operations. Whether you are building an automated ingestion pipeline that scans a local directory for incoming CSV files, or validating business date logic such as determining leap years, mastering core Java I/O APIs is essential. This guide provides production-grade implementations for reading property files using class loaders, processing directory contents safely, and handling date calculations without relying on external dependencies.

If you are scaling these file-processing applications into containerized production environments, you may also benefit from reviewing our guide on Dockerizing a Spring Boot Application with MySQL. For developers transitioning legacy codebases to modern language specifications, understanding Java 17 Records and Pattern Matching with Examples can significantly streamline your configuration data transfer objects.

Reading and Parsing Properties Files in Java

The java.util.Properties class represents a persistent set of properties. It can be saved to a stream or loaded from a stream, with each key and its corresponding value in the property list being a string. In enterprise applications, property files are typically stored in the src/main/resources directory of a Maven or Gradle project so they are packaged correctly into the build output (JAR or WAR).

Consider a real-world scenario where an application must ingest a comma-separated list of authorized role IDs from a configuration file to enforce role-based access control (RBAC). Instead of altering Java source code whenever a role is added or removed, the IDs are maintained externally.

Step 1: Create the Properties File

Create a file named javaex.properties inside your source or resource directory. Populate it with a comma-separated string of identifiers:

application.id.roleIds = '53','121','63','46','43','71','45','36','64'

Step 2: Implement the Java Reader Program

The following production-ready class uses the classpath resource loader to fetch the file, loads it into a Properties instance, extracts the string by its key, and splits it into an array for processing.

package com.javatbrains.practice;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class CommaSeparated {
    public static void main(String[] args) {
        // Use try-with-resources to ensure the InputStream is closed automatically
        try (InputStream stream = CommaSeparated.class.getClassLoader().getResourceAsStream("javaex.properties")) {
            
            if (stream == null) {
                throw new FileNotFoundException("javaex.properties not found in the classpath.");
            }

            Properties prop = new Properties();
            prop.load(stream);

            String roleIds = prop.getProperty("application.id.roleIds");
            
            if (roleIds != null && !roleIds.isEmpty()) {
                // Split the comma-separated string into an array
                String[] roleIdArray = roleIds.split(",");
                
                for (int i = 0; i < roleIdArray.length; i++) {
                    // Trim whitespace if necessary, though direct print matches source logic
                    System.out.println("Role id is = " + roleIdArray[i].trim());
                }
            } else {
                System.out.println("Property 'application.id.roleIds' is missing or empty.");
            }

        } catch (IOException e) {
            System.err.println("Failed to read configuration file: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Execution Output

Role id is = '53'
Role id is = '121'
Role id is = '63'
Role id is = '46'
Role id is = '43'
Role id is = '71'
Role id is = '45'
Role id is = '36'
Role id is = '64'

Detailed Breakdown of the Implementation

  • getClassLoader().getResourceAsStream("javaex.properties"): Locates the file relative to the classpath. This prevents hardcoded absolute file paths like C:/config/javaex.properties, making the code platform-independent and portable across Windows, Linux, and macOS.
  • Properties.load(stream): Reads an input stream containing a property list syntax and maps keys to string values.
  • String.split(","): Breaks the retrieved single-line configuration value into individual string tokens based on comma delimiters.
  • Try-with-Resources: Replaces traditional try-catch blocks for I/O streams, preventing memory leaks by auto-closing the input stream upon execution completion.

Listing Files in a Directory

Automated batch processing often requires traversing a local or network directory to discover files waiting for ingestion. The java.io.File class provides basic utilities for querying directory contents.

The program below targets a root directory path, retrieves an array of string filenames, and prints out the absolute file paths along with the total count.

package com.javatbrains.practice;

import java.io.File;

public class ListOfFiles {
    public static void main(String[] args) {
        // Specify target directory path (ensure path exists and has read permissions)
        String targetDirPath = "C:/";
        File directory = new File(targetDirPath);

        if (!directory.exists()) {
            System.err.println("Error: The specified directory does not exist.");
            return;
        }

        if (!directory.isDirectory()) {
            System.err.println("Error: The specified path is not a directory.");
            return;
        }

        // Retrieve list of file and directory names
        String[] paths = directory.list();

        if (paths != null) {
            for (String path : paths) {
                System.out.println(directory.getAbsolutePath() + (directory.getAbsolutePath().endsWith(File.separator) ? "" : File.separator) + path);
            }
            System.out.println("Total no. of files and directories : " + paths.length);
        } else {
            System.out.println("Directory is empty or an I/O error occurred.");
        }
    }
}

Determining Leap Years Programmatically

Date logic is a recurring requirement in financial, scheduling, and reporting applications. A leap year occurs every year that is evenly divisible by 4, except for century years that are not evenly divisible by 400.

package com.javatbrains.practice;

public class LeapYearChecker {
    public static boolean isLeapYear(int year) {
        if (year % 400 == 0) {
            return true;
        } else if (year % 100 == 0) {
            return false;
        } else {
            return year % 4 == 0;
        }
    }

    public static void main(String[] args) {
        int[] testYears = {2000, 2020, 2023, 2024, 1900};
        
        for (int year : testYears) {
            System.out.println("Year " + year + " is a leap year? " + isLeapYear(year));
        }
    }
}

Comparison of Java File and Configuration Approaches

When designing solutions for property loading and file traversal, developers can choose between legacy I/O classes, modern NIO.2 APIs, or external frameworks. The table below compares these approaches.

Feature / Task Legacy java.util.Properties & File Modern java.nio.file (NIO.2) Spring Boot @ConfigurationProperties
Performance Moderate; synchronous blocking I/O. High; optimized for fast file system access. High; cached at application startup.
Boilerplate Code High; manual stream handling, splitting, and null checks. Low; fluent builder APIs and streams. Minimal; automatic type binding via annotations.
Error Handling Requires explicit try-catch blocks and stream closing. Uses unchecked IOException variants and safe iterators. Fails fast on startup if properties are misconfigured.
Use Case Simple standalone scripts and legacy apps. Complex file system crawling and monitoring. Enterprise microservices and web applications.

Real-World Edge Cases and Mitigation Strategies

Writing code that passes basic testing is only half the battle. Production environments introduce unpredictable states that can crash applications if unhandled.

  • Edge Case 1: Missing Property Files (NullPointerException)
    If the application cannot locate javaex.properties inside the classpath, getResourceAsStream() returns null. Passing this null stream directly into Properties.load() throws a NullPointerException. Mitigation: Always validate that the input stream is not null before invoking load methods, and throw a descriptive custom exception.
  • Edge Case 2: Special Characters and Character Encodings
    By default, the Properties.load(InputStream) method uses ISO-8859-1 encoding. If your configuration values contain international characters, emojis, or non-Latin scripts, they will render as corrupted text (mojibake). Mitigation: For Java 9 and newer, use Properties.load(Reader) combined with InputStreamReader initialized with StandardCharsets.UTF_8.
  • Edge Case 3: Inaccessible Directories and Permission Denied Errors
    When running directory scanners in production (such as on restricted Linux servers or locked-down Windows environments), executing directory.list() on a restricted folder returns null rather than throwing an exception. Mitigation: Always check for null return arrays and verify file readability using File.canRead() before iterating.

Troubleshooting Common Configuration Issues

When deploying Java file utility classes, developers frequently run into environment-specific bugs. Use this checklist to resolve them:

  • Symptom: java.io.FileNotFoundException when running a packaged JAR file.
    Root Cause: The code is using an absolute file path pointing to a local development machine directory (e.g., C:/projects/...) that does not exist on the production server.
    Solution: Refactor your file loading logic to rely strictly on classpath loading via ClassLoader.getResourceAsStream() or externalize the path via an environment variable.
  • Symptom: Property keys return null even though the file is present.
    Root Cause: The property key requested in code contains a typo, or the property file was placed in the wrong build output folder (e.g., placed in the root project directory instead of src/main/resources).
    Solution: Verify your build tool configuration (Maven/Gradle) to ensure resource filtering is enabled and files are copied to the target output classpath during compilation.

Summary

Effectively managing configuration files and local storage in Java requires strict adherence to robust input/output practices. Key takeaways include:

  • Externalize configuration parameters into .properties files to keep code clean and environment-agnostic.
  • Always utilize classpath loaders (getResourceAsStream()) instead of rigid absolute file paths for configuration assets.
  • Implement defensive programming checks (null stream validation, array null checks, and explicit exception handling) to protect against unexpected runtime failures.
  • Leverage modern APIs or enterprise frameworks when scaling applications into containerized cloud environments.

Comments

Popular posts from this blog

JVM, JRE and JDK in Java

Understanding JVM, JRE, and JDK in Java Every Java developer encounters three fundamental acronyms on their first day: JVM , JRE , and JDK . Misunderstanding these foundational components leads to runtime exceptions, deployment failures, and incorrect build environments. This guide breaks down the precise architectural boundaries, memory structures, and deployment requirements of each component. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. The core problem this guide solves is ambiguous environment configuration. Developers often attempt to run production applications using a Development Kit when a Runtime Environment suffices, or they deploy platform-incompatible binaries to minimal Li...

Prime, Fibonacci and Factorial number with example in java

Mastering Prime, Fibonacci, and Factorial Algorithms in Java Prime Number Validation Workflow Prime Number Validation Workflow 1 Boundary Check Verify if the input number is less than or equal to 1. 2 Even Number Check Check if divisible by 2 and return true only if number is 2. 3 Square Root Limit Calculate integer square root as the upper loop bound. 4 Odd Factor Loop Iterate through odd integers up to limit checking divisibility. Figure: Prime Number Validation Workflow Technical coding interviews frequently test foundational algorithmic competence through three classic mathematical problems: identifying prime numbers, generating Fibonacci sequences, and calculating factorials. While these concepts originate in basic arithmetic, writing production-grade Java code to solve them requires careful attention to time complexity, memory allocation, boundary conditions, and overflow behavior. This tutorial provides rigorous, optimized Java i...

How to insert images into database using JDBC?

How to Insert Images into a Database Using JDBC Storing binary data such as images, PDFs, and application assets is a frequent requirement in enterprise software engineering. While relational databases like MySQL are optimized for structured tabular text and numeric data, they also provide robust binary storage types—specifically BLOB (Binary Large Object) variants—to handle arbitrary byte streams. When interacting with relational stores through Java, the Java Database Connectivity (JDBC) API serves as the primary bridge. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. This technical guide demonstrates how to persist image files from a local file system directly into a MySQL database usin...