如何在 Java 中从属性文件中读取数据?
javaobject oriented programmingprogramming
Properties 是 Hashtable 类的子类,它表示一组持久属性。Properties 可以保存到流中或从流中加载。属性列表中的每个键及其对应的值都是一个字符串。
Properties 文件可用于在 Java 中外部化配置并存储键值对。Properties 类的 Properties.load() 方法可以方便地以键值 对的形式加载 .properties 文件。
语法
public class Properties extends Hashtable
credentials.properties file
示例
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