从 Resource 资源文件夹下获取文件
方式一
1
2
|
// 必须要以/开头,否则读取到的是类文件同级目录下的文件,见[从类文件的相对路径获取文件]
InputStream inputStream = this.getClass().getResourceAsStream("/static/logo.png");
|
方式二
1
2
|
// 直接获取文件的二进制流
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/static/logo.png")
|
从类文件的相对路径获取文件
(默认情况下,maven编译时只会复制源码的java文件到编译目录,所以java文件之外的文件都读不到。如果需要在同级目录下放置文件,则需要配置POM文件如下)
1
2
|
// 读取类文件同级目录下的文件
InputStream inputStream = this.getClass().getResourceAsStream("file.txt");
|
POM文件
1
2
3
4
5
6
7
8
9
10
11
|
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.txt</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
|
从运行目录获取文件
方式一
1
|
String currentPathStr = System.getProperty("user.dir");
|
方式二
1
2
3
4
5
6
7
|
File file = new File("");
try {
String currentPathStr = file.getCanonicalPath();
System.err.println("path4:" + path4);
} catch (IOException e) {
e.printStackTrace();
}
|