java使用Properties读取配置文件

2022-11-19

# 获取配置文件

## getResourceAsStream

> 可以读取 非jar包时的工程目录里的文件、jar包里的文件。非工程内文件不能用这个方法。

1. Class.getResourceAsStream(String path)

path不以’/'开头时默认是从此类(执行该方法的类)所在的包下取资源,以’/'开头则是从ClassPath下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。

2. Class.getClassLoader.getResourceAsStream(String path)

默认则是从ClassPath根下获取,path不能以’/'开头,最终是由ClassLoader获取资源。

3. ServletContext.getResourceAsStream(String path)

默认从WebAPP根目录下取资源,Tomcat下path是否以’/'开头无所谓,当然这和具体的容器实现有关。
 

## 用处

```

要加载的文件和.class文件在同一目录下,例如:com.x.y 下有类me.class ,同时有资源文件myfile.xml

me.class.getResourceAsStream("myfile.xml");

```

```

在me.class目录的子目录下,例如:com.x.y 下有类me.class ,同时在 com.x.y.file 目录下有资源文件myfile.xml

那么,应该有如下代码:

me.class.getResourceAsStream("file/myfile.xml");

```

```

不在me.class目录下,也不在子目录下,例如:com.x.y 下有类me.class ,同时在 com.x.file 目录下有资源文件myfile.xml

那么,应该有如下代码:

me.class.getResourceAsStream("/com/x/file/myfile.xml");

```

## 总结

前面有"/"根,代表了项目工程根目录。不带根时,默认工作目录就是当前类的目录。


 

# 读取内容

```JAVA

package java.util;

public class Properties extends Hashtable<Object,Object> {}

```

```JAVA

Properties properties = new Properties();

properties.load(Kis.class.getResourceAsStream("/fff/asdasd.pro"));

properties.load(new FileInputStream("/media/xys/ty/repos/testcuk/src/main/resources/fff/asdasd.pro"));

System.out.println(properties.getProperty("fuck"));

```