如何從 Java 中讀取屬性檔案中的資料?
屬性是 Hashtable 類的子類,表示持久屬性集。屬性可以儲存到流中或從流中載入。屬性列表中的每個鍵及其對應的值都是字串。
屬性檔案可用於 Java 中,用於將配置外化並存儲鍵值對。Properties.load() 方法的 Properties 類可方便地以鍵值對的形式載入.properties檔案。
語法
public class Properties extends Hashtable
credentials.properties 檔案
示例
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
廣告