Reading Properties file in Java

To read a properties file in Java, you can use the Properties class from the java.util package. This class provides methods for reading and writing properties from a properties file.

Here's an example of how you can read a properties file in Java:

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

public class Main {
  public static void main(String[] args) {
    Properties prop = new Properties();
    InputStream input = null;

    try {
      // load the properties file
      input = new FileInputStream("config.properties");
      prop.load(input);

      // read the properties
      String username = prop.getProperty("username");
      String password = prop.getProperty("password");

      System.out.println("Username: " + username);
      System.out.println("Password: " + password);
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (input != null) {
        try {
          input.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}

This code creates a Properties object and an InputStream object, and then uses the load method of the Properties object to read the properties file. It then uses the getProperty method to read the "username" and "password" properties, and prints them to the console.

Note that the load method reads the properties file as a stream of characters, so you will need to use an InputStream object to read the file. You can also use the loadFromXML method to read an XML-based properties file.

You can also use the setProperty method to set the value of a property in the properties file, and the store or storeToXML methods to write the properties to the file.