Creating a properties file in Java and eclipse

前端 未结 1 826
广开言路
广开言路 2021-01-08 00:13

I want to create a config.properties file, in which I want to store all the key and values instead of hard coding them in the Java code.

However, I do not know how t

相关标签:
1条回答
  • 2021-01-08 00:48
    1. Create a new file from file menu Or press Ctrl+N
    2. In place of file name write config.properties then click finish

    Then you can add properties your property file like this

    dbpassword=password
    database=localhost
    dbuser=user
    

    Example of loading properties

    public class App {
      public static void main(String[] args) {
    
        Properties prop = new Properties();
        InputStream input = null;
    
        try {
    
            input = new FileInputStream("config.properties");
    
            // load a properties file
            prop.load(input);
    
            // get the property value and print it out
            System.out.println(prop.getProperty("database"));
            System.out.println(prop.getProperty("dbuser"));
            System.out.println(prop.getProperty("dbpassword"));
    
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
      }
    }
    

    By Edit

    By Edit

    0 讨论(0)
提交回复
热议问题