如何从 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP