读取resources下的资源

这里我通过一个普通的SpringBoot项目进行测试,当然其他项目也都是通用的。

将其中的Test修改为你的类名即可:

读取resources下的资源

java;gutter:true; import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.ClassPathResource;</p> <p>import java.io.*; import java.net.URLDecoder; import java.util.Objects;</p> <p>/*<em> * @ClassName Test * @Author zhangzhixi * @Description * @Date 2022-8-11 16:48 * @Version 1.0 </em>/ @Slf4j public class Test { public static void main(String[] args) throws IOException { log.info("\n==============测试读取resources下的资源=============="); String fileName = "application.yml"; log.info("\n==============第一版=============="); function1(fileName); log.info("\n==============第二版=============="); function2(fileName); log.info("\n==============第三版=============="); function3(fileName); log.info("\n==============第四版=============="); function4(fileName); log.info("\n==============第五版=============="); function5(fileName); log.info("\n==============第六版=============="); function6(fileName); log.info("\n==============第七版=============="); function7(fileName); }</p> <pre><code>/** * 通过类路径找到resources下的资源 * * @param fileName 资源名称 * @throws IOException 异常 */ private static void function1(String fileName) throws IOException { String path = Objects.requireNonNull(Test.class.getClassLoader().getResource("")).getPath(); System.out.println(path); String filePath = path + fileName; System.out.println(filePath); getFileContent(filePath); } /** * 直接通过文件名getPath来获取路径 * * @param fileName 文件名 * @throws IOException IO异常 */ public static void function2(String fileName) throws IOException { String path = Objects.requireNonNull(Test.class.getClassLoader().getResource(fileName)).getPath(); System.out.println(path); //如果路径中带有中文会被URLEncoder,因此这里需要解码 String filePath = URLDecoder.decode(path, "UTF-8"); System.out.println(filePath); getFileContent(filePath); } /** * 直接使用getResourceAsStream方法获取流 * springboot项目中需要使用此种方法,因为jar包中没有一个实际的路径存放文件 * * @param fileName 文件名 * @throws IOException IO异常 */ public static void function3(String fileName) throws IOException { InputStream in = Test.class.getClassLoader().getResourceAsStream(fileName); getFileContent(in); } /** * 直接使用getResourceAsStream方法获取流 * 如果不使用getClassLoader,可以使用getResourceAsStream("/配置测试.txt")直接从resources根路径下获取 * * @param fileName 文件名 * @throws IOException IO异常 */ public static void function4(String fileName) throws IOException { InputStream in = Test.class.getResourceAsStream("/" + fileName); getFileContent(in); } /** * 通过ClassPathResource类获取,建议SpringBoot中使用 * springboot项目中需要使用此种方法,因为jar包中没有一个实际的路径存放文件 * * @param fileName 文件名 * @throws IOException IO异常 */ public static void function5(String fileName) throws IOException { ClassPathResource classPathResource = new ClassPathResource(fileName); InputStream inputStream = classPathResource.getInputStream(); getFileContent(inputStream); } /** * 通过绝对路径获取项目中文件的位置(不能用于服务器) * * @param fileName 文件名 * @throws IOException IO异常 */ public static void function6(String fileName) throws IOException { // 获取项目的绝对路径 String rootPath = System.getProperty("user.dir"); String filePath = rootPath + File.separatorChar + "src" + File.separatorChar + "main" + File.separatorChar + "resources" + File.separatorChar + fileName; getFileContent(filePath); } /** * 通过绝对路径获取项目中文件的位置(不能用于服务器) * * @param fileName 文件名 * @throws IOException IO异常 */ public static void function7(String fileName) throws IOException { //参数为空 File directory = new File(""); //规范路径:getCanonicalPath() 方法返回绝对路径,会把 ..\ 、.\ 这样的符号解析掉 String rootCanonicalPath = directory.getCanonicalPath(); String filePath = rootCanonicalPath + File.separatorChar + "src" + File.separatorChar + "main" + File.separatorChar + "resources" + File.separatorChar + fileName; getFileContent(filePath); } /** * 根据文件路径读取文件内容 * * @param fileInPath 文件路径 */ public static void getFileContent(Object fileInPath) throws IOException { BufferedReader br = null; if (fileInPath == null) { return; } if (fileInPath instanceof String) { br = new BufferedReader(new FileReader((String) fileInPath)); } else if (fileInPath instanceof InputStream) { br = new BufferedReader(new InputStreamReader((InputStream) fileInPath)); } String line; while (true) { assert br != null; if ((line = br.readLine()) == null) { break; } System.out.println(line); } br.close(); } </code></pre> <p>}

Original: https://www.cnblogs.com/zhangzhixi/p/16576869.html
Author: Java小白的搬砖路
Title: 读取resources下的资源

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/612618/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Gorm 的黑魔法

    开发过程中,看到同事的代码写了这么一段: db = db.Session(&gorm.Session{Context: db.Statement.Context}).Fir…

    数据库 2023年6月9日
    098
  • 解决Laravel报错No application encryption key has been specified的问题

    可能有些小伙伴从git上拉下来的项目在本地运行时会报No application encryption key has been specified的错,如图: 这是因为.env文…

    数据库 2023年6月14日
    074
  • 8 int和Integer的区别

    数据类型 int是基本数据类型,Integer是int的包装类,属于引用类型 初始值 int的初始值为0,Integer的初始值为null 存储位置 int是直接存储在栈中的,In…

    数据库 2023年6月6日
    096
  • 第十五章 Spring动态代理开发

    创建原始对象 public class UserServiceImpl implements UserService{ @Override public void register…

    数据库 2023年6月14日
    0110
  • datatable 转化成xml以及json

    datatable dt=xxx获取 赋值给应用的字段 var pp=dt.row[0][“datatable里面的字段”].tostring() var …

    数据库 2023年6月9日
    084
  • phpstrom以及webstrom等jetbrains全家桶激活方法

    因为最近重新安装了phpstrom,所以在网上找了许多激活方式,各种激活码和加公众号都试过了,没有一个能用的,直到我找到了以下的方式,亲测可用: 原理是我们通过代码搜索其他授权服务…

    数据库 2023年6月14日
    0157
  • Ajax请求下载文件的解决方案

    写这个博客之前我并不清楚 ajax请求是下载不了文件的 😅 这段时间在写一个自己的项目,用到了ajax下载文件,请求到了controller层并返回文件下载成功 但是浏览器就是没有…

    数据库 2023年6月9日
    0247
  • 一张图弄懂sql的连接查询

    无意中看到一张图,非常直观的表现出了sql连接查询的结果集,对连接查询的理解十分有帮助,所以收藏了下来。 其中红色部分为可以查询出的数据,白色部分为不能查询出的数据 Origina…

    数据库 2023年6月14日
    099
  • LeetCode刷题笔记-简单入门题

    分割平衡字符串 在一个 平衡字符串 中,’L’ 和 ‘R’ 字符的数量是相同的。 给你一个平衡字符串 s,请你将它分割成尽可能多的平…

    数据库 2023年6月11日
    093
  • 【MySQL】试题 — 31道巩固 SQL 语句的练习题

    1.取得每个部门最高薪水的人员名称先拿出各部门的最高工资,再与(最高工资对应的人员名录表)对接为临时表。 [En] First take out the maximum salar…

    数据库 2023年5月24日
    095
  • MySQL快速创建800w条测试数据表&深度分页

    MySQL快速创建800w条测试数据表&深度分页 如果一条一条插入普通表的话,效率太低下,但内存表插入速度是很快的,可以先建立一张内存表,插入数据后,在导入到普通表中。 1…

    数据库 2023年6月14日
    097
  • 我的第一次校招

    2018-09-26 23:40:03 虽然是第一次参加,但这次的笔试完成结果让我不是很满意,因为有几道超简单的字符串编程没有做,忘了或者是想复杂了,还有一些概念题不是很清楚,自己…

    数据库 2023年6月16日
    0122
  • 模板语法之继承

    什么是模板继承 模板继承就是指可以使父模板的内容重用,子模板直接继承父模板的全部内容,并可以覆盖父模板中相应的块 继承的语法 &#x7236;&#x6A21;&am…

    数据库 2023年6月14日
    092
  • 【数据库】– 15个小技巧,拿捏SQL优化 【转载】

    前言 sql优化是一个大家都比较关注的热门话题,无论你在面试,还是工作中,都很有可能会遇到。 如果某天你负责的某个线上接口,出现了性能问题,需要做优化。那么你首先想到的很有可能是优…

    数据库 2023年6月6日
    0113
  • login方法访问不到解决过程

    背景:由于项目登录模块之前使用传统的字符验证码,干扰又太严重,经常会有输入十次以上才能蒙对的情况。于是提出让改为滑动验证码(斗鱼,B站等等)。如图所示: 原有的: 要改的: 这个实…

    数据库 2023年6月11日
    0137
  • 20 行代码!带你快速构建基础文本搜索引擎 ⛵

    💡 作者:韩信子@ShowMeAI📘 机器学习实战系列:https://www.showmeai.tech/tutorials/41📘 深度学习实战系列:https://www.s…

    数据库 2023年6月14日
    083
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球