如何在 Eclipse 中将 Java 属性文件添加到我的 Java 项目中

2022-09-02 02:14:35

我以前使用Unix来编译和编辑我的Java。因为我已经在类文件所在的当前工作目录中使用了属性文件。现在我已经切换到Eclipse IDE。我不知道如何在Eclipse中添加相同的属性文件。请帮帮我。


答案 1
  1. 在 Java 资源文件夹下创建文件夹“资源”(如果您的项目没有)。
    1. 创建具有以下值的 config.properties 文件。

enter image description here

/Java Resources/resources/config.properties

用于加载属性。

Properties prop = new Properties();
InputStream input = null;

try {

      input = getClass().getClassLoader().getResourceAsStream("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();
        }
    }
}

答案 2

在包资源管理器中,右键单击包并选择“新建 ->文件”,然后输入文件名(包括“.properties”后缀)。