在Java和eclipse中创建属性文件

sta*_*ar1 15 java eclipse

我想创建一个config.properties文件,我想在其中存储所有的键和值,而不是在Java代码中对它们进行硬编码.

但是,我不知道如何在eclipse中创建属性文件.我研究并找到了有关如何读取属性文件的帮助.我需要有关如何创建它的帮助.

以下是我的具体问题:

  1. 可以在eclipse中创建config.properties文件,并将数据直接输入到它中,就像config.properties类似于文本编辑器一样?
  2. 如果可以直接创建,请告诉我创建此属性文件的步骤吗?
  3. 我假设可以创建属性文件,就像创建java项目,java类等一样(通过右键单击包或项目级别).这是正确的假设吗?
  4. 或者创建属性文件并向其添加数据需要通过java编码来完成?

我将非常感谢任何帮助.

mir*_*sif 15

  1. 从文件菜单创建新文件或按Ctrl + N.
  2. 代替文件名写 config.properties然后单击完成

然后,您可以像这样添加属性文件的属性

dbpassword=password
database=localhost
dbuser=user
Run Code Online (Sandbox Code Playgroud)

加载属性的示例

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();
            }
        }
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在此输入图像描述