dea*_*ean 7 java servlets file
我正在使用servlet来硬编码数据库连接的详细信息,所以如果进行任何更改,我必须重新编译代码.所以相反,我想使用一个.properties文件(我稍后可以修改)并将其用作我的数据库连接的源.
问题是我不知道如何读取属性文件.有人可以帮我看一下这个文件吗?
. . .
// 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存在. - ......
您可以查看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)中.
您可以在他们的网站上找到更多示例.
您可以使用java.util.Properties
| 归档时间: |
|
| 查看次数: |
22754 次 |
| 最近记录: |