美文网首页
SpringBoot 读取 resources 下面的文件

SpringBoot 读取 resources 下面的文件

作者: sT丶 | 来源:发表于2022-08-24 13:41 被阅读0次

修改POM文件

这一步的作用,是为了将文件都打包进去,防止出现在IDE里面可以,但是打成jar包后出现文件找不到的情况

 <build>
        <finalName>xxx-api</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <includeSystemScope>true</includeSystemScope>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <filtering>false</filtering>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
    </build>

读取文件

假如在 resources 目录下有个 abc.config文件


        ClassPathResource classPathResource = new ClassPathResource("/abc.config");
        InputStream inputStream = classPathResource.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);

        StringBuilder strBuilder = new StringBuilder();

        char[] chars = new char[1024];
        // 循环读取客户端发送的数据
        while (true) {
            int read = inputStreamReader.read(chars);
            if (read != -1) {
                // 输出客户端发送的数据
                String str = new String(chars, 0, read);
                strBuilder.append(str);
            } else {
                break;
            }
        }

        inputStreamReader.close();
        inputStream.close();

        System.out.println(strBuilder);

相关文章

网友评论

      本文标题:SpringBoot 读取 resources 下面的文件

      本文链接:https://www.haomeiwen.com/subject/xoxogrtx.html