Properties 类 如何读取properties文件中的数据
时间: 2024-05-24 11:10:32 浏览: 12
Properties 类是 Java 中用于读取和处理 properties 文件的工具类。以下是如何使用 Properties 类读取 properties 文件中的数据的步骤:
1. 创建 Properties 实例:
Properties prop = new Properties();
2. 使用 load() 方法加载 properties 文件:
FileInputStream fis = new FileInputStream("config.properties");
prop.load(fis);
3. 通过 key 获取对应的 value:
String value = prop.getProperty("key");
其中,key 是 properties 文件中的属性名,value 是对应的属性值。
完整的示例代码:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ReadPropertiesFile {
public static void main(String[] args) {
Properties prop = new Properties();
try {
FileInputStream fis = new FileInputStream("config.properties");
prop.load(fis);
String name = prop.getProperty("name");
String version = prop.getProperty("version");
String author = prop.getProperty("author");
System.out.println("Name: " + name);
System.out.println("Version: " + version);
System.out.println("Author: " + author);
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代码会读取 config.properties 文件中的 name、version 和 author 属性的值,并输出到控制台。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)