jar包读取resource静态资源路径出现!号;getFile()背锅!

本文讲述了在Java中,如何在jar包中正确读取静态资源,强调了使用`getResourceAsStream()`方法而非`ResourceUtil.getFile()`的原因,后者在jar环境下由于依赖于本地文件系统而失效,而前者则基于类加载器加载资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 【jar包可行】在jar包中正确读取静态资源

使用getResourceAsStream()

InputStream stream = getClass()
                .getClassLoader()
                .getResourceAsStream("names.txt");
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            String line;
            while ( (line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

【具体解释】getFile为什么在jar包中不行

我们本地读取文件的时候是使用spring自带的ResourceUtil.getFile("classpath:xxxx.txt"),该方法读取是本地的绝对路径,在我们ide开发工具中是没有问题的,因为文件就在磁盘上存储,读取当然也是通过文件存储的磁盘地址读取,但是我们的项目一旦 打包 成jar文件后,我们的所有文件都会在JVM中运行(都是加载到JVM中的),所以使用ResourceUtil.getFile("classpath:xxxx.txt")方法是不可以读取到的,在JVM中是没有绝对路径的,所有的路径都是依托于读取文件的当前类对应的classload来加载的,所以我们需要先获取到当前类的classload,然后通过classload的路径找文件相对于classload的相对路径。

【IDEA可行】在idea中可行但jar中不可行的读取resourece下静态文件的方法

方法一:

这种方案在jar包中也不行
        String path = this.getClass().getClassLoader().getResource("names.txt").getFile();//注意getResource("")里面是空字符串
        String filePath = null;//如果路径中带有中文会被URLEncoder,因此这里需要解码
        Scanner myReader = null;
        try {
            filePath = URLDecoder.decode(path, "UTF-8");
            System.out.println("打印路径:");
            System.out.println(filePath);
            File file = new File(filePath);
            myReader = new Scanner(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
        }
        myReader.close();

方法二:

 File file = ResourceUtils.getFile(patternNameFile);
            Scanner myReader = new Scanner(file);
            while (myReader.hasNextLine()) {
                String data = myReader.nextLine();
            }
            myReader.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }

 参考博客:ResouceUtils.getFile()取不到Jar中资源文件源码-腾讯云开发者社区-腾讯云 (tencent.com)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值