温馨提示×

如何读取Java Properties文件

小樊
82
2024-08-23 23:24:28
栏目: 编程语言

在Java中,可以使用java.util.Properties类来读取Properties文件。下面是一个简单的示例代码:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class Main {
    public static void main(String[] args) {
        Properties properties = new Properties();
        
        try {
            FileInputStream file = new FileInputStream("config.properties");
            properties.load(file);
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        String value = properties.getProperty("key");
        System.out.println("Value for key: " + value);
    }
}

在上面的示例中,首先创建了一个Properties对象,然后通过FileInputStream类加载Properties文件并使用load方法将文件中的属性加载到Properties对象中。最后,可以使用getProperty方法获取文件中指定属性的值。

0