文件读取方法一(本地可用)
ClassPathResource classPathResource = new ClassPathResource("img.png");
File file = classPathResource.getFile();
FileInputStream inputStream = new FileInputStream(file);
文件读取方法二 (线上服务可用)
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("img.png");
Resource resource = resources[0];
if (resource == null) {
throw new BizException("图片读取失败!");
}
String tempPath = System.getProperty("java.io.tmpdir") + "tomcat_" + System.currentTimeMillis();
String tempFile = tempPath + File.separator + "img.png";
File file = new File(tempPath);
if (!file.exists()) {
file.mkdir();
}
ByteStreams.copy(resource.getInputStream(), new FileOutputStream(new File(tempFile)));
- 该方法将jar包中的文件以字节流读取存在相应的临时文件目录下,可以正常进行线上使用
- new FileInputStream(new File(tempPath + File.separator + “img.png”)
文件存放目录如下
文件目录读取
ClassPathResource classPathResource = new ClassPathResource("msyh.ttf");
String path = classPathResource.getURL().getPath();
String pathStr = path.substring(0, path.lastIndexOf("/"));
FontSettings.setFontsFolder(pathStr, true);
项目中的jar包读取
<dependency>
<groupId>xiaomi</groupId>
<artifactId>xiaomi</artifactId>
<version>1.2</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/xxx.jar</systemPath>
</dependency>
<dependency>
<groupId>xiaomi</groupId>
<artifactId>xiaomi</artifactId>
<version>1.2</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/xxxx.jar</systemPath>
</dependency>
- 方法2为项目中之前使用,项目部署上去回报错,原因是打包之后并没有带到服务器之中,随后改为方法一,将文件存放在resource当中可以使用