In Java, one common way to store app configuration data is by using properties files. Properties files are simple text files that contain key-value pairs. Here's an example of how you can read and write app configuration data using properties files in Java:

Step 1: Create a properties file (config.properties) with some sample data:

             
app.name=MyApp
app.version=1.0
app.author=John Doe

             

Step 2: Read the properties file in Java and print the values:

             java
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class AppConfig {
    public static void main(String[] args) {
        Properties properties = new Properties();
        try (FileInputStream fis = new FileInputStream("config.properties")) {
            properties.load(fis);

            String appName = properties.getProperty("app.name");
            String appVersion = properties.getProperty("app.version");
            String appAuthor = properties.getProperty("app.author");

            System.out.println("App Name: " + appName);
            System.out.println("App Version: " + appVersion);
            System.out.println("App Author: " + appAuthor);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

             

Step 3: Run the Java program. Make sure the config.properties file is in the same directory as your Java program.

Output:

             
App Name: MyApp
App Version: 1.0
App Author: John Doe

             

Step 4: Update the properties file and write new data:

             java
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class AppConfig {
    public static void main(String[] args) {
        Properties properties = new Properties();
        try (FileInputStream fis = new FileInputStream("config.properties")) {
            properties.load(fis);

            // Update properties
            properties.setProperty("app.version", "2.0");
            properties.setProperty("app.author", "Jane Smith");

            // Write updated properties to file
            try (FileOutputStream fos = new FileOutputStream("config.properties")) {
                properties.store(fos, "Updated config properties");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

             

Step 5: Run the Java program again to update the properties file.

Output:

             
Updated config properties

             

By following this guide, you can easily read and write app configuration data in Java using properties files.

Was this article helpful?
YesNo

Similar Posts