zoukankan      html  css  js  c++  java
  • 读取properties文件中的内容

     看情况有时候某些属性值在很多地方要用,而且可能会有改动,就可以把它们存在properties文件中。

     当然也可以准备一个静态类来放。

    //调用方法的静态代码块
    private static String getStr = "";
    static {
      try {
        Properties properties = PropertiesUtil.readProperties("sys.properties");
        //Str是文件中配置的名字部分
        //例:文件中存了几个属性,其中一个是Str=test
        //那么取出来的数据中,getStr=test(取出来的都是字符串)
        getStr = properties.getProperty("Str");
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

     

    //方法类
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    public class PropertiesUtil {
      public static Properties readProperties(String fileName) throws IOException {
        Properties properties = new Properties();
        InputStream inStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
        if (inStream == null) {
          throw new RuntimeException(fileName + " not found");
        }
    
        properties.load(inStream);
        return properties;
      }
    }


    方法二
    这个比上面的方法简单很多,我更喜欢用这个
    import java.util.ResourceBundle;

    private static final String Str;

     static{
      ResourceBundle rb = ResourceBundle.getBundle("sys");
      Str=rb.getString("Str");
     }

     
  • 相关阅读:
    基于XML的声明式事务控制
    spring中JdbcTemplate使用
    四种常用的通知类型(xml)
    AOP配置步骤(XML)
    12388. 图论割边
    12389. 割点
    12206. 电缆网络
    12178. 破坏牛棚
    java反射笔记
    java单元测试
  • 原文地址:https://www.cnblogs.com/IceBlueBrother/p/8423019.html
Copyright © 2011-2022 走看看