gpt4 book ai didi

java - 在 Java 和 Eclipse 中创建属性文件

转载 作者:搜寻专家 更新时间:2023-10-30 19:59:17 30 4
gpt4 key购买 nike

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

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

这是我的具体问题:

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

我将不胜感激任何帮助。

最佳答案

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

然后你可以像这样在你的属性文件中添加属性

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

}
}

By Edit

By Edit

关于java - 在 Java 和 Eclipse 中创建属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30010833/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com