在 Java 和 Eclipse 中创建属性文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30010833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:58:48  来源:igfitidea点击:

Creating a properties file in Java and eclipse

javaeclipse

提问by star1

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.

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

However, I do not know how to create a properties file in eclipse. I researched and found help on how to read a properties file. I need help with how to create it.

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

Here are my specific questions:

以下是我的具体问题:

  1. Can a config.propertiesfile be created in eclipse, and data be typed directly into it as though the config.properties is similar to text editor?
  2. If it can be directly created, the can you please let me know the steps to create this properties file?
  3. I am assuming that properties file can be created just like how java project, java class etc are created (by right clicking at package or project level). Is this correct assumption?
  4. Or creating a properties file and adding data to it needs to be done by java coding?
  1. 是否可以config.properties在 Eclipse 中创建文件,并将数据直接输入其中,就像 config.properties 类似于文本编辑器一样?
  2. 如果可以直接创建,能否告诉我创建这个属性文件的步骤?
  3. 我假设可以像创建 java 项目、java 类等一样创建属性文件(通过在包或项目级别右键单击)。这是正确的假设吗?
  4. 或者创建一个属性文件并向其中添加数据需要通过java编码来完成?

I will greatly appreciate any help.

我将不胜感激任何帮助。

采纳答案by mirmdasif

  1. Create a new file from file menu Or press Ctrl+N
  2. In place of file name write config.propertiesthen click finish
  1. 从文件菜单创建一个新文件或按Ctrl+N
  2. 代替文件名写入 config.properties然后单击完成

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

通过编辑