Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีอ่านข้อมูลจาก Properties File ใน Java


Properties เป็นคลาสย่อยของ Hashtable แทนชุดคุณสมบัติที่ persistent สามารถ save/load จาก stream ได้ แต่ละ key และ value ใน property list เป็น string

Properties file ใช้ใน Java เพื่อ externalize การตั้งค่า และเก็บ key-value pairs เมธอด Properties.load() โหลดไฟล์ .properties เป็น key-value pairs ได้สะดวก

ไวยากรณ์

public class Properties extends Hashtable

ไฟล์ credentials.properties


วิธีอ่านข้อมูลจาก Properties File ใน Java

ตัวอย่าง

import java.io.*;
import java.util.*;

public class ReadPropertiesFileTest {
    public static void main(String args[]) throws IOException {
        Properties prop = readPropertiesFile("credentials.properties");
        System.out.println("username: " + prop.getProperty("username"));
        System.out.println("password: " + prop.getProperty("password"));
    }

    public static Properties readPropertiesFile(String fileName) throws IOException {
        FileInputStream fis = null;
        Properties prop = null;
        try {
            fis = new FileInputStream(fileName);
            prop = new Properties();
            prop.load(fis);
        } catch(FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch(IOException ioe) {
            ioe.printStackTrace();
        } finally {
            fis.close();
        }
        return prop;
    }
}

ผลลัพธ์

username: admin password: admin@123