在Java和Eclipse中创建属性文件 [英] Creating a properties file in Java and eclipse

查看:143
本文介绍了在Java和Eclipse中创建属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

以下是我的具体问题:


  1. 是否可以在eclipse中创建 config.properties 文件,并直接在其中键入数据
    ,就像config.properties类似于
    文本编辑器?

  2. 如果可以直接创建它,可以让我知道创建该属性文件的
    步骤吗?

  3. 我假设可以创建属性文件,就像创建Java
    项目,java类等的方式一样(通过在包或
    项目级别上单击鼠标右键)。

  4. 还是要创建属性文件并向其中添加数据,需要通过Java编码完成

  1. Can a config.properties file 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. 从文件菜单创建新文件,或按 Ctrl + N

  2. 代替文件名,写 config.properties 然后单击完成

  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

加载属性示例

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

  }
}

这篇关于在Java和Eclipse中创建属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆