举个例子上文中用的properties
时间: 2023-11-27 11:51:21 浏览: 32
好的,假设你正在编写一个Java应用程序,需要读取一个名为config.properties的属性文件来配置应用程序。下面是一个示例config.properties文件:
```
#database configuration
db.host=localhost
db.port=3306
db.name=mydatabase
db.user=myusername
db.password=mypassword
#application configuration
app.title=MyApp
app.version=1.0
app.author=John Doe
```
在Java中,你可以使用以下代码读取这个属性文件:
```java
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class AppConfig {
private static final String CONFIG_FILE = "config.properties";
private static Properties properties;
static {
properties = new Properties();
try {
FileInputStream inputStream = new FileInputStream(CONFIG_FILE);
properties.load(inputStream);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getDbHost() {
return properties.getProperty("db.host");
}
public static int getDbPort() {
return Integer.parseInt(properties.getProperty("db.port"));
}
public static String getDbName() {
return properties.getProperty("db.name");
}
public static String getDbUser() {
return properties.getProperty("db.user");
}
public static String getDbPassword() {
return properties.getProperty("db.password");
}
public static String getAppTitle() {
return properties.getProperty("app.title");
}
public static String getAppVersion() {
return properties.getProperty("app.version");
}
public static String getAppAuthor() {
return properties.getProperty("app.author");
}
}
```
这个示例代码中,我们定义了一个名为AppConfig的Java类,其中包含了静态方法来获取不同的属性值。在类的静态块中,我们使用FileInputStream和Properties类来读取config.properties文件,并将其保存在一个静态的properties变量中。然后,我们定义了一系列静态方法来获取各种属性的值,例如getDbHost()方法返回db.host属性的值。这样,其他的Java类就可以通过调用AppConfig类中的这些静态方法来获取属性值,并用这些值来配置应用程序。