java如何读取resources目录中的文件呢?

欣喜 Java经验 发布时间:2024-02-07 16:18:05 阅读数:4520 1
下文笔者讲述java代码读取resource目录中文件的方法及示例分享,如下所示
我们都知道SpringBoot打包生成jar文件后
  resource目录中的文件会存储在class目录中
  那么我们如何才能读取文件呢?
  下文笔者将通过示例的方式一一道来,如下所示

文本文件读取

使用Spring框架
 可使用ClassPathResource来读取文件流
  将文件读取成字符串才进行二次操作
   如:
     properties,txt,csv,SQL,json等 

例:

String data = "";
ClassPathResource cpr = new ClassPathResource("static/test.txt");
try {
    byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
    data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
    LOG.warn("IOException", e);
}
例:读取文件的工具类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import org.springframework.core.io.ClassPathResource;
public final class ClassPathResourceReader {
    /**
     * path:文件路径
     * @since JDK 1.8
     */
    private final String path;
    /**
     * content:文件内容
     * @since JDK 1.6
     */
    private String content;
    public ClassPathResourceReader(String path) {
        this.path = path;
    }
    public String getContent() {
        if (content == null) {
            try {
                ClassPathResource resource = new ClassPathResource(path);
                BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
                content = reader.lines().collect(Collectors.joining("\n"));
                reader.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
        return content;
    }
}
 
//使用方法
String content = new ClassPathResourceReader("log4j.properties").getContent();

非文本文件读取

 例:读取resource目录下的xls文件
     我们可参考以下代码

ClassPathResource classPathResource = new ClassPathResource("test/template_export.xls"");
InputStream inputStream = classPathResource.getInputStream();
//生成目标文件
File somethingFile = File.createTempFile("template_export_copy", ".xls");
try {
    FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
    IOUtils.closeQuietly(inputStream);
}

版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202402/17072939177943.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者