pps.load(new FileInputStream(RedisUtil.class.getResource("/resources").toURI().getPath()+"project.properties")); 怎么理解
时间: 2024-04-28 16:27:23 浏览: 17
这段代码是在Java中读取一个名为"project.properties"的配置文件。它首先通过`RedisUtil.class.getResource("/resources")`获取到该类所在的资源路径,然后通过`.toURI().getPath()`方法获取该路径的URI,并将其转换为字符串表示。最后,通过`new FileInputStream`读取该文件并将其加载到`pps`对象中。
相关问题
src/main/resources 配置下的配置文件,使用new FileInputStream(RedisUtil.class.getResource("/resources").toURI().getPath()+"project.properties") 无法读出
可能是因为你的代码中使用了错误的路径,导致无法读取配置文件。你可以尝试使用以下方法来读取配置文件:
1. 直接使用 ClassLoader 来读取配置文件,代码如下:
```
InputStream inputStream = RedisUtil.class.getClassLoader().getResourceAsStream("project.properties");
```
2. 使用 Class.getResourceAsStream() 方法来读取配置文件,代码如下:
```
InputStream inputStream = RedisUtil.class.getResourceAsStream("/project.properties");
```
以上两种方法都可以读取 src/main/resources 目录下的配置文件。如果还是无法读取到配置文件,可能是配置文件的路径或文件名有误,你可以再次检查一下。
properties.load(fileInputStream)设置编码格式
在使用 Properties 类加载 properties 文件时,它默认使用 ISO 8859-1 编码格式。如果你需要使用其他编码格式,可以通过以下步骤实现:
1. 首先,将 properties 文件的编码格式转换为 Java 支持的 Unicode 编码格式。可以使用 Java 内置的 native2ascii 工具来实现。例如,如果你的 properties 文件使用的是 UTF-8 编码格式,可以使用以下命令将其转换为 Unicode 编码格式:
```
native2ascii -encoding UTF-8 input.properties output.properties
```
这将把名为 input.properties 的 UTF-8 编码文件转换为名为 output.properties 的 Unicode 编码文件。
2. 然后,使用 FileInputStream 和 InputStreamReader 类加载 Unicode 编码格式的 properties 文件。例如,可以使用以下代码加载名为 output.properties 的 Unicode 编码格式的文件:
```java
FileInputStream fis = new FileInputStream("output.properties");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
Properties properties = new Properties();
properties.load(isr);
isr.close();
```
在这个例子中,我们首先使用 FileInputStream 和 InputStreamReader 类加载 Unicode 编码格式的 properties 文件。然后,我们创建一个 Properties 对象,并使用 load() 方法加载 InputStream。请注意,我们使用的是 Unicode 编码格式的 InputStream。最后,我们关闭 InputStreamReader 对象。
这样,你就可以在加载 properties 文件时使用指定的编码格式了。