首先我们要明确一点,springboot项目是能读取到一些特殊文件夹下的文件比如static

所以我们要把需要被读取到的文件放在resources/static下面

第一步:把需要被读取到的文件放在resources/static下面

第二步:修改配置文件

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
		<!-- 一定要加这个,要不然会一直报文件不存在-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
    </build>

第三步:使用

String certPath = "static/apiclient_cert.pem";
        System.out.println("开始查看绝对路径");
        ClassPathResource classPathResource = new ClassPathResource(certPath);
        File file = classPathResource.getFile();

        System.out.println("文件路径myconfig=============" + file.getAbsolutePath());
        InputStream certStream = new FileInputStream(file);

#但注意会有好几个坑:
第一个坑:
你还是会报找不到这个路径下的文件,原因是你编译后生成的target目录下没有加载这个文件,
解决:
需要在pom里面那家的配置见上面

第二个坑(大坑):
上生产linux的时候,你会发现还是会报找不到这个路径下的文件
解决:
方法一

// 生产
        String certPath = "/usr/tomcat/apache-tomcat-9.0.53/webapps/apiclient_cert.p12";
        // 测试
      /*  String certPath = "E:\\aprogram\\zycx\\src\\main\\resources\\templates\\apiclient_cert.p12";*/
        File file = new File(certPath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();

方法二:

1. 使用resource.getInputStream()读取文件内容
2. 缓存到临时文件,使用临时文件路径进行读取

String tempPath = System.getProperty("java.io.tmpdir")+"tomcat_"+System.currentTimeMillis();
String tempFile = tempPath+File.separator+fileName;
Resource resource = new DefaultResourceLoader().getResource("classpath:META-INF/resources"+filePath);
if (resource == null) {
    return "";
}

File file = new File(tempPath);
if (!file.exists()) {
    file.mkdir();
}
IOUtil.cp(resource.getInputStream(),new FileOutputStream(new File(tempFile)));

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐