在 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
Creating a properties file in Java and eclipse
提问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:
以下是我的具体问题:
- 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? - If it can be directly created, the can you please let me know the steps to create this properties file?
- 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?
- Or creating a properties file and adding data to it needs to be done by java coding?
- 是否可以
config.properties
在 Eclipse 中创建文件,并将数据直接输入其中,就像 config.properties 类似于文本编辑器一样? - 如果可以直接创建,能否告诉我创建这个属性文件的步骤?
- 我假设可以像创建 java 项目、java 类等一样创建属性文件(通过在包或项目级别右键单击)。这是正确的假设吗?
- 或者创建一个属性文件并向其中添加数据需要通过java编码来完成?
I will greatly appreciate any help.
我将不胜感激任何帮助。
采纳答案by mirmdasif
- Create a new file from file menu Or press Ctrl+N
- In place of file name write config.propertiesthen click finish
- 从文件菜单创建一个新文件或按Ctrl+N
- 代替文件名写入 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();
}
}
}
}
}