Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách đọc dữ liệu từ file properties trong Java?

Lớp Properties là subclass của Hashtable đại diện cho tập thuộc tính bền vững. Properties có thể lưu vào stream hoặc tải từ stream. Mỗi khóa và giá trị tương ứng trong danh sách thuộc tính là một chuỗi.

File Properties trong Java dùng để externalize cấu hình và lưu cặp key-value. Phương thức Properties.load() tiện lợi để load file .properties dạng key-value pairs.

Cú pháp

public class Properties extends Hashtable

File credentials.properties

Cách đọc dữ liệu từ file properties trong Java?

Ví dụ

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; 
    } 
}

Kết quả

username: admin password: admin@123