导入properties时的坑

不用框架的方法导入properties文件时,除了把文件放在resource下面,网上查到的方法都找不到文件,一直报空指针异常。

自己设坑:一开始为了测试方便,把property放在了本地绝对路径下,使用下面代码能够导入。

      File f = new File("D:/x.properties");
      Properties p = new Properties();
      p.load(new FileInputStream(f));

后要改相对路径,变为new File("x.properties")时发现导不进去,报异常。

各种尝试,发现在文件名前加上/,就能不报错,能够顺路找到值。

出现个情况:把x.properties内的内容修改一下后,得到的key,value值还是原来的x.properties的内容,

找遍全局,发现全项目就一个x.properties文件,并没有第二份。奇怪了。

后来发现p 导入的是原来放在绝对路径D盘根目录下的x.properties对手。一但删除掉该文件,系统又开始报错空指针。

就会多想起上代码:PropertyUtil

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertyUtil {

  public static Properties getResources(String filename) {
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
    Properties prop = new Properties();
    try {
      prop.load(is);
    } catch (IOException e) {
      e.printStackTrace();
    }
    if (is != null) {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return prop;
  }
}

  


Properties prop = new Properties();
prop = getResources("handler.properties");


原文地址:https://www.cnblogs.com/DaTouDaddy/p/7562947.html