如何在Eclipse中将Java Properties文件添加到我的Java项目中
我之前使用Unix来编译和编辑我的Java。 在那里,我已经在我的当前工作目录中使用了属性文件,其中存在类文件。 现在我已切换到Eclipse IDE。 我不知道如何在Eclipse中添加相同的属性文件。 请帮帮我。
如果在当前工作目录中有属性文件,它应该在Unix中正常工作。 另一个选择是将属性文件添加到类路径并使用this.getClass().getClassLoader().getResourceAsStream("xxxxx.properties");
获取输入流this.getClass().getClassLoader().getResourceAsStream("xxxxx.properties");
更多这里
在包资源管理器中,右键单击该包并选择New – > File,然后输入包含“.properties”后缀的文件名。
- 如果您的项目没有,请在Java Resources文件夹下创建文件夹“resources”。
- 使用以下值创建config.properties文件。
/ 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(); } } }
脚步:
- 右键单击要创建.properties文件的任何包,或根据需要创建新包
- 现在选择new然后选择文件(如果你找不到文件然后转到你的包的位置并在那里创建它)
- 现在将其命名为yourfilename.properties
如果您使用’from existing source’选项在eclipse中创建了Java Project,那么它应该像以前一样工作。 更准确地说File> New Java Project 。 在“内容”部分中,选择“ 从现有源创建项目 ”,然后选择现有项目文件夹。 向导将负责其余的工作。
- 在eclipse中右键单击项目中要创建属性文件的文件夹
- 在搜索filter类型文件和连续窗口中的New-> Other->给出扩展名为.properties的文件的名称
要创建属性类,请选择要在其中创建属性文件的包。
右键单击包并选择其他。 现在选择File并使用(.properties)后缀键入文件名。 例如:db.properties。 比点击完成。 现在,您可以在此属性文件中编写代码。
如果您正在使用核心java,请通过右键单击项目来创建文件( properties
)。 如果文件存在于包或src文件夹中,则会抛出找不到文件的错误