• Java 从资源文件(.properties)中读取数据


    在Java工程目录src下,创建一个后缀为.properties的文件,例如db.properties

    文件中的内容如下(键=值):

    name=mk
    age=123
    address=China

    在程序中读取资源文件中的内容

     1 import java.io.File;
     2 import java.io.FileInputStream;
     3 import java.io.FileNotFoundException;
     4 import java.io.FileReader;
     5 import java.io.IOException;
     6 import java.util.Properties;
     7 
     8 public class Demo01 {
     9   static Properties properties = null;  // 用于读取和处理资源文件中的信息
    10   static {                              // 类加载的时候被执行一次
    11     properties = new Properties();
    12     // 加载方式一
    13     try {
    14       properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
    15     } catch (IOException e) {
    16       e.printStackTrace();
    17     }
    18     
    19     // 加载方式二
    20 //    try {
    21 //      properties.load(new FileInputStream(new File("src/db.properties")));
    22 //    } catch (FileNotFoundException e) {
    23 //      e.printStackTrace();
    24 //    } catch (IOException e) {
    25 //      e.printStackTrace();
    26 //    }
    27     
    28     // 加载方式三
    29 //    try {
    30 //      properties.load(new FileReader(new File("src/db.properties")));
    31 //    } catch (FileNotFoundException e) {
    32 //      e.printStackTrace();
    33 //    } catch (IOException e) {
    34 //      e.printStackTrace();
    35 //    }
    36   }
    37   
    38   public static void main(String[] args) {
    39     System.out.println("name: " + properties.getProperty("name"));  // 根据提供的键找到对应的值
    40     System.out.println("age: " + properties.getProperty("age"));
    41     System.out.println("address: " + properties.getProperty("address"));
    42   }
    43 }

    执行结果

    name: mk
    age: 123
    address: China
  • 相关阅读:
    poj3181(Dollar Dayz)
    poj3666(Making the Grade)
    poj2392(Space Elevator)
    hdu5288(OO’s Sequence)
    hdu5289(Assignment)
    快学scala
    Spark Checkpointing
    Spark Performance Tuning (性能调优)
    Spark Memory Tuning (内存调优)
    Sparkstreaming and Kafka
  • 原文地址:https://www.cnblogs.com/Satu/p/11079745.html
Copyright © 2020-2023  润新知