如何在Java中读取属性文件?

dea*_*ean 7 java servlets file

我正在使用servlet来硬编码数据库连接的详细信息,所以如果进行任何更改,我必须重新编译代码.所以相反,我想使用一个.properties文件(我稍后可以修改)并将其用作我的数据库连接的源.

问题是我不知道如何读取属性文件.有人可以帮我看一下这个文件吗?

Mar*_*erg 7

   . . .
   // create and load default properties
   Properties defaultProps = new Properties();
   FileInputStream in = new FileInputStream("defaultProperties");
   defaultProps.load(in);
   in.close();

   // create application properties with default
   Properties applicationProps = new Properties(defaultProps);

   // now load properties from last invocation
   in = new FileInputStream("appProperties");
   applicationProps.load(in);
   in.close();
   . . .
Run Code Online (Sandbox Code Playgroud)

示例来自这里Properties(Java)

Properties可以抛出异常的方法.- 文件路径无效时(FileNotFoundException).请尝试创建一个File对象并检查是否File存在. - ......

  • 你应该在复制并粘贴你的答案之前阅读这条消息! (2认同)

Pio*_*otr 5

您可以查看Apache Commons Configuration.使用它你可以读取这样的属性文件:

Configuration config = new PropertiesConfiguration("user.properties");
String connectionUrl = config.getString("connection.url");
Run Code Online (Sandbox Code Playgroud)

有关文件位置的此信息可能也很重要:

如果未指定绝对路径,则将在以下位置自动搜索该文件:

  • 在当前目录中
  • 在用户主目录中
  • 在类路径中

因此,如果在servlet中读取属性文件,则应将属性文件放在类路径中(例如,在WEB-INF/classes)中.

您可以在他们的网站上找到更多示例.


tru*_*ity 3

您可以使用java.util.Properties

  • 但我使用了 Properties 方法,但它抛出 FileNotFound 异常 我的代码: Properties prop = new Properties(); prop.load(new FileInputStream("file.properties")); (2认同)
  • 您的属性文件需要位于类路径中。 (2认同)