Java 读取resources下的资源文件

您所在的位置:网站首页 java如何读取配置文件 Java 读取resources下的资源文件

Java 读取resources下的资源文件

2024-05-24 13:28| 来源: 网络整理| 查看: 265

Web项目中应该经常有这样的需求,在maven项目的resources目录下放一些文件。比如一些配置文件,资源文件等。文件的读取方式有好几种方式,本文会对常用的读取方式做一个总结,并说明一下应该注意的地方。

准备工作新建一个spring-test 的maven项目,resources目录下创建测试文件conf.properties、city_code.json (json文件夹下)。添加pom依赖

使用 FileUtils、IOUtils等工具类,需要引入 commons-io jar包。

org.springframework.boot spring-boot-starter-web 2.2.7.RELEASE commons-io commons-io 2.6 一、通过ClassLoader读取文件

ClassLoader.getResourceAsStream()获取文件输入流

public void loadPropertiesFile() throws IOException { Properties properties = new Properties(); properties.load(this.getClass().getClassLoader().getResourceAsStream("conf.properties")); log.info(properties.getProperty("file.max.size")); }

ClassLoader.getResourceAsStream()获取文件的URL

public void loadJsonFile() throws IOException { //获取文件的URL URL url = this.getClass().getClassLoader().getResource("json/city_code.json"); String content = FileUtils.readFileToString(new File(url.getPath()), StandardCharsets.UTF_8); log.info(content); }二、通过Class读取文件

Class.getResourceAsStream()获取文件的输入流

public void loadPropertiesFile() throws IOException { Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream("/conf.properties")); log.info(proper


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3