如何从 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

更新时间:2023 年 9 月 14 日

30K+ 浏览量

开启你的 职业生涯

通过完成课程获取认证

开始学习
广告
© . All rights reserved.