溫馨提示×

idea怎么讀取properties文件

小億
154
2024-03-20 10:04:52
欄目: 編程語言

在Java中,可以使用Properties類來讀取properties文件。下面是一個簡單的例子:

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

public class ReadPropertiesFile {

    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 value1 = properties.getProperty("key1");
        String value2 = properties.getProperty("key2");

        System.out.println("Value for key1: " + value1);
        System.out.println("Value for key2: " + value2);
    }
}

在上面的例子中,我們創(chuàng)建了一個Properties對象,然后使用FileInputStream來加載properties文件。接著使用load方法將文件中的屬性加載到Properties對象中。最后可以通過getProperty方法獲取屬性的值。

需要注意的是,要確保config.properties文件存在并且位于正確的路徑下。

0