java如何调用config
时间: 2023-10-03 11:08:19 浏览: 47
在Java中调用配置文件通常使用Properties类来实现。下面是一个简单的示例:
假设你有一个名为config.properties的配置文件,内容如下:
```
db.url=jdbc:mysql://localhost:3306/mydb
db.username=root
db.password=123456
```
然后,你可以使用以下代码来读取配置文件中的值:
```java
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
Properties properties = new Properties();
try {
FileInputStream fileInputStream = new FileInputStream("config.properties");
properties.load(fileInputStream);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
String dbUrl = properties.getProperty("db.url");
String dbUsername = properties.getProperty("db.username");
String dbPassword = properties.getProperty("db.password");
System.out.println("DB URL: " + dbUrl);
System.out.println("DB Username: " + dbUsername);
System.out.println("DB Password: " + dbPassword);
}
}
```
上述代码通过创建Properties对象并使用load()方法加载配置文件,然后使用getProperty()方法根据键获取对应的值。
当然,你也可以根据具体需求对配置文件进行修改、新增、删除等操作。