如何解决Maven项目中正确读取resources文件夹路径的问题?
- 内容介绍
- 文章标签
- 相关推荐
本文共计734个文字,预计阅读时间需要3分钟。
读取`resources`下文件的方法,网上有如下解答:
问:`new FileInputStream(src/main/resources/all.properties)` 和 `new FileInputStream(.\\src\\main\\resources\\all.properties)` 上面两个无法读取 Maven 依赖源文件目录下的文件。
答:这是因为这两种方式都是基于文件系统的绝对路径或相对路径,而 Maven 依赖的文件通常不在当前项目的文件系统中。要读取这些文件,可以使用以下方法:
1. 使用`ClassLoader`的`getResourceAsStream`方法:javaInputStream inputStream=getClass().getClassLoader().getResourceAsStream(all.properties);
2. 使用`InputStream`的`getResourceAsStream`方法:javaInputStream inputStream=this.getClass().getResourceAsStream(/all.properties);
这两种方法都可以正确读取 Maven 依赖源文件目录下的文件。
本文共计734个文字,预计阅读时间需要3分钟。
读取`resources`下文件的方法,网上有如下解答:
问:`new FileInputStream(src/main/resources/all.properties)` 和 `new FileInputStream(.\\src\\main\\resources\\all.properties)` 上面两个无法读取 Maven 依赖源文件目录下的文件。
答:这是因为这两种方式都是基于文件系统的绝对路径或相对路径,而 Maven 依赖的文件通常不在当前项目的文件系统中。要读取这些文件,可以使用以下方法:
1. 使用`ClassLoader`的`getResourceAsStream`方法:javaInputStream inputStream=getClass().getClassLoader().getResourceAsStream(all.properties);
2. 使用`InputStream`的`getResourceAsStream`方法:javaInputStream inputStream=this.getClass().getResourceAsStream(/all.properties);
这两种方法都可以正确读取 Maven 依赖源文件目录下的文件。

