java加载配置文件的三种方式
比如我们要加载db.properties文件
如图:
比如我们要加载source目录下的db.properties文件。就有以下几种方式
第一种是文件io流:
public static void load1() throws Exception{ //文件真实路径 String fileName="E:/Workspace/SSHDemo/Source/db.properties"; Properties p=new Properties(); InputStream is=new FileInputStream(new File(fileName)); p.load(is); System.out.println(p); }
第二种:相对路径:
//相对路径 public static void load2() throws Exception{ Properties p=new Properties(); //InputStream is=ClassLoader.getSystemResourceAsStream("db.properties");
InputStream is=Thread.currentThread().getContextClassLoader().getSystemResourceAsStream("db.properties"); p.load(is); System.out.println(p); } public static void load2_1() throws Exception{ Properties p=new Properties(); InputStream is=SourceLoader.class.getClassLoader().getSystemResourceAsStream("db.properties"); p.load(is); System.out.println(p); }
如果我们要获取src(类包)下的db.properties又该怎么处理呢?
//相对于类路径 properties文件盒java放在一起 public static void load3() throws Exception{ Properties p=new Properties(); //InputStream is=ClassLoader.getSystemResourceAsStream("db.properties"); InputStream is=SourceLoader.class.getResourceAsStream("db.properties"); p.load(is); System.out.println(p); }
三种方式都打印出来db.properties文件中的信息: