Java 如何从属性文件中读取数据

Java 如何从属性文件中读取数据

Properties 是 Hashtable 类的子类,表示一个持久的属性集。 Properties 可以保存到流或从流加载。属性列表中的每个键及其对应的值都是一个字符串。

在Java中, Properties 文件可用于外部化配置并存储 键值对 。Properties 类的 Properties.load() 方法 方便地以 键值对 的形式加载 .properties文件。

语法

public class Properties extends Hashtable

credentials.properties文件

Java 如何从属性文件中读取数据

示例

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程