封装一个PropUtils工具类,使用 Properties 读取 properties 的文件 a) 提供一个 getProperty(String key) 方法,获取 配置文件指定的键对应的 值 b) 要求 读取配置文件的代码,写在 静态代码块 中
时间: 2023-05-20 17:02:55 浏览: 75
好的,我可以回答这个问题。以下是封装一个PropUtils工具类的代码:
```
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropUtils {
private static Properties props;
static {
props = new Properties();
InputStream is = PropUtils.class.getClassLoader().getResourceAsStream("config.properties");
try {
props.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key) {
return props.getProperty(key);
}
}
```
这个工具类使用了静态代码块来读取配置文件,提供了一个getProperty方法来获取指定键对应的值。你可以将config.properties文件放在classpath下,然后使用PropUtils.getProperty("key")来获取对应的值。
相关问题
如何打包一个Java项目,并且运行jar包,同时还要读取properties配置文件
打包Java项目并运行jar包,需要使用Java的打包工具,如Maven或Gradle。
以下是使用Maven打包Java项目并运行jar包的步骤:
1. 在项目根目录下创建一个名为pom.xml的Maven配置文件,其中包含项目依赖和插件配置。
2. 在配置文件中添加以下插件:
```xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.example.MainClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
```
这将生成一个可执行的jar文件,并将项目的主类指定为程序的入口点。
3. 在配置文件中添加以下依赖项:
```xml
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
</dependencies>
```
这将下载并包含commons-lang3库,以便您可以在程序中使用它。
4. 执行以下命令打包项目:
```
mvn package
```
这将在target目录下生成一个名为project-name.jar的可执行文件。
5. 运行jar文件:
```
java -jar project-name.jar
```
6. 在程序中读取properties配置文件:
```java
Properties prop = new Properties();
InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties");
prop.load(input);
String value = prop.getProperty("key");
```
在程序中可以使用Properties类读取配置文件。在这个例子中,我们可以从classpath中读取名为config.properties的配置文件,并获取其中的属性值。
properties读取配置文件获取配置文件的关键代码是
使用Java读取properties文件的关键代码如下:
```java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadPropertiesFile {
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();
}
}
}
}
}
```
其中,我们通过创建一个Properties对象来操作properties文件。首先,我们需要创建一个输入流,将properties文件加载到Properties对象中,然后就可以通过getProperty()方法获取对应的属性值了。最后,我们需要关闭输入流。