Java实现读取resources目录下的文件路径的九种方式

目录
  • 前情提要
  • 方式一
  • 方式二
  • 方式三
  • 方式四(重要)
  • 方式五(重要)
  • 方式六(重要)
  • 方式七
  • 方式八
  • 方式九

前情提要

本文中提供了九种方式获取resources目录下文件的方式。其中打印文件的方法如下:

    /**
     * 根据文件路径读取文件内容
     *
     * @param fileInPath
     * @throws IOException
     */
    public static void getFileContent(Object fileInPath) throws IOException {
        BufferedReader br = null;
        if (fileInPath == null) {
            return;
        }
        if (fileInPath instanceof String) {
            br = new BufferedReader(new FileReader(new File((String) fileInPath)));
        } else if (fileInPath instanceof InputStream) {
            br = new BufferedReader(new InputStreamReader((InputStream) fileInPath));
        }
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        br.close();
    }

方式一

主要核心方法是使用getResource和getPath方法,这里的getResource("")里面是空字符串

    public void function1(String fileName) throws IOException {
        String path = this.getClass().getClassLoader().getResource("").getPath();//注意getResource("")里面是空字符串
        System.out.println(path);
        String filePath = path + fileName;
        System.out.println(filePath);
        getFileContent(filePath);
    }

方式二

主要核心方法是使用getResource和getPath方法,直接通过getResource(fileName)方法获取文件路径,注意如果是路径中带有中文一定要使用URLDecoder.decode解码。

    /**
     * 直接通过文件名getPath来获取路径
     *
     * @param fileName
     * @throws IOException
     */
    public void function2(String fileName) throws IOException {
        String path = this.getClass().getClassLoader().getResource(fileName).getPath();//注意getResource("")里面是空字符串
        System.out.println(path);
        String filePath = URLDecoder.decode(path, "UTF-8");//如果路径中带有中文会被URLEncoder,因此这里需要解码
        System.out.println(filePath);
        getFileContent(filePath);
    }

方式三

直接通过文件名+getFile()来获取文件。如果是文件路径的话getFile和getPath效果是一样的,如果是URL路径的话getPath是带有参数的路径。如下所示:

url.getFile()=/pub/files/foobar.txt?id=123456
url.getPath()=/pub/files/foobar.txt

使用getFile()方式获取文件的代码如下:

    /**
     * 直接通过文件名+getFile()来获取
     *
     * @param fileName
     * @throws IOException
     */
    public void function3(String fileName) throws IOException {
        String path = this.getClass().getClassLoader().getResource(fileName).getFile();//注意getResource("")里面是空字符串
        System.out.println(path);
        String filePath = URLDecoder.decode(path, "UTF-8");//如果路径中带有中文会被URLEncoder,因此这里需要解码
        System.out.println(filePath);
        getFileContent(filePath);
    }

方式四(重要)

直接使用getResourceAsStream方法获取流,上面的几种方式都需要获取文件路径,但是在SpringBoot中所有文件都在jar包中,没有一个实际的路径,因此可以使用以下方式。

    /**
     * 直接使用getResourceAsStream方法获取流
     * springboot项目中需要使用此种方法,因为jar包中没有一个实际的路径存放文件
     *
     * @param fileName
     * @throws IOException
     */
    public void function4(String fileName) throws IOException {
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
        getFileContent(in);
    }

方式五(重要)

主要也是使用getResourceAsStream方法获取流,不使用getClassLoader可以使用getResourceAsStream("/配置测试.txt")直接从resources根路径下获取,SpringBoot中所有文件都在jar包中,没有一个实际的路径,因此可以使用以下方式。

    /**
     * 直接使用getResourceAsStream方法获取流
     * 如果不使用getClassLoader,可以使用getResourceAsStream("/配置测试.txt")直接从resources根路径下获取
     *
     * @param fileName
     * @throws IOException
     */
    public void function5(String fileName) throws IOException {
        InputStream in = this.getClass().getResourceAsStream("/" + fileName);
        getFileContent(in);
    }

方式六(重要)

通过ClassPathResource类获取文件流,SpringBoot中所有文件都在jar包中,没有一个实际的路径,因此可以使用以下方式。

    /**
     * 通过ClassPathResource类获取,建议SpringBoot中使用
     * springboot项目中需要使用此种方法,因为jar包中没有一个实际的路径存放文件
     *
     * @param fileName
     * @throws IOException
     */
    public void function6(String fileName) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(fileName);
        InputStream inputStream = classPathResource.getInputStream();
        getFileContent(inputStream);
    }

方式七

通过绝对路径获取项目中文件的位置,只是本地绝对路径,不能用于服务器获取。

    /**
     * 通过绝对路径获取项目中文件的位置(不能用于服务器)
     * @param fileName
     * @throws IOException
     */
    public void function7(String fileName) throws IOException {
        String rootPath = System.getProperty("user.dir");//E:\WorkSpace\Git\spring-framework-learning-example
        String filePath = rootPath + "\\chapter-2-springmvc-quickstart\\src\\main\\resources\\"+fileName;
        getFileContent(filePath);
    }

方式八

通过new File("")获取当前的绝对路径,只是本地绝对路径,不能用于服务器获取。

    /**
     * 通过绝对路径获取项目中文件的位置(不能用于服务器)
     * @param fileName
     * @throws IOException
     */
    public void function8(String fileName) throws IOException {
        //参数为空
        File directory = new File("");
        //规范路径:getCanonicalPath() 方法返回绝对路径,会把 ..\ 、.\ 这样的符号解析掉
        String rootCanonicalPath = directory.getCanonicalPath();
        //绝对路径:getAbsolutePath() 方法返回文件的绝对路径,如果构造的时候是全路径就直接返回全路径,如果构造时是相对路径,就返回当前目录的路径 + 构造 File 对象时的路径
        String rootAbsolutePath =directory.getAbsolutePath();
        System.out.println(rootCanonicalPath);
        System.out.println(rootAbsolutePath);
        String filePath = rootCanonicalPath + "\\chapter-2-springmvc-quickstart\\src\\main\\resources\\"+fileName;
        getFileContent(filePath);
    }

方式九

主要是通过设置环境变量,将文件放在环境变量中,原理也是通过绝对路径获取。
示例中我设置了一个环境变量:TEST_ROOT=E:\\WorkSpace\\Git\\spring-framework-learning-example

 System.getenv("TEST_ROOT");
 System.getProperty("TEST_ROOT")

通过设置环境变量的方式,然后通过绝对路径获取文件

    /**
     * 通过绝对路径获取项目中文件的位置
     *
     * @param fileName
     * @throws IOException
     */
    public void function9(String fileName) throws IOException {
        System.setProperty("TEST_ROOT","E:\\WorkSpace\\Git\\spring-framework-learning-example");
        //参数为空
        String rootPath = System.getProperty("TEST_ROOT");
        System.out.println(rootPath);
        String filePath = rootPath + "\\chapter-2-springmvc-quickstart\\src\\main\\resources\\"+fileName;
        getFileContent(filePath);
    }

到此这篇关于Java实现读取resources目录下的文件路径的九种方式的文章就介绍到这了,更多相关Java 读取resources目录下文件路径内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • java(包括springboot)读取resources下文件方式实现

    本文主要介绍了java(包括springboot)读取resources下文件方式实现,分享给大家,具体如下: 1.使用项目内路径读取,该路径只在开发工具中显示,类似:src/main/resources/resource.properties.只能在开发工具中使用,部署之后无法读取.(不通用) File file = new File("src/main/resources/resource.properties"); @Test public void testReadFile2(

  • java读取resources文件详解及实现代码

    java读取resources文件详解及实现代码 Java项目中,经常需要将资源文件打包放在项目中,然后在项目中去读取对应的文件. 实现代码: String str = ReadFile.read(getClass().getResourceAsStream("sence/"+file)); public static String read(InputStream inputStream) { BufferedReader reader = null; String laststr

  • Java实现的读取资源文件工具类ResourcesUtil实例【可动态更改值的内容】

    本文实例讲述了Java实现的读取资源文件工具类ResourcesUtil.分享给大家供大家参考,具体如下: package com.gcloud.common; import java.io.Serializable; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; impor

  • 浅谈Java工程读取resources中资源文件路径的问题

    正常在Java工程中读取某路径下的文件时,可以采用绝对路径和相对路径,绝对路径没什么好说的,相对路径,即相对于当前类的路径.在本地工程和服务器中读取文件的方式有所不同,以下图配置文件为例. 本地读取资源文件 java类中需要读取properties中的配置文件,可以采用文件(File)方式进行读取: File file = new File("src/main/resources/properties/basecom.properties"); InputStream in = new

  • Java实现读取resources目录下的文件路径的九种方式

    目录 前情提要 方式一 方式二 方式三 方式四(重要) 方式五(重要) 方式六(重要) 方式七 方式八 方式九 前情提要 本文中提供了九种方式获取resources目录下文件的方式.其中打印文件的方法如下:     /**      * 根据文件路径读取文件内容      *      * @param fileInPath      * @throws IOException      */     public static void getFileContent(Object fileIn

  • Springboot 项目读取Resources目录下的文件(推荐)

    需求描述:企业开发过程中,经常需要将一些静态文本数据放到Resources目录下,项目启动时或者程序运行中,需要读取这些文件. 读取Resources目录下文件的方法 /** * @Description: 读取resources 目录下的文件 * @Author: ljj * @CreateDate: 2020/11/3 17:20 * @UpdateUser: * @UpdateDate: * @UpdateReakem * @param filePath * @Return: java.l

  • 解读classpath读取resources目录下的文件

    目录 classpath读取resources目录下文件 1.class.getResource() 2.getClassLoader().getResource() 4.批量读取 5.如果配置文件中要引用这个文件的路径呢? 总结 classpath读取resources目录下文件 最近在springboot+maven的项目中去读取资源文件的时候,报了找不到文件的错误. 由此展开了对maven项目编译前和编译后的目录结构的了解,以及对java的classpath的理解. 首先: 由Maven构

  • 详解SpringBoot读取resource目录下properties文件的常见方式

    个人理解 在企业开发中,我们经常需要自定义一些全局变量/不可修改变量或者参数来解决大量的变量重复问题,当需要这个全局变量时,只需要从配置文件中读取即可,根据开发中常见的情况,可以分为以下两种情况,分别是: 配置文件为SpringBoot默认的application.properties文件中的自定义参数 加载自定义properties文件中的自定义参数,比如xxx.properties的自定义参数 加载SpringBoot默认的application.properties 准备工作 server

  • Android开发实现读取assets目录下db文件的方法示例

    本文实例讲述了Android开发实现读取assets目录下db文件的方法.分享给大家供大家参考,具体如下: 最近准备打算写一个关于天气预报的app,偶然的机会在一大神的博客上看到了一个获取天气的api,获取天气是通过城市的cityID,项目中准备通过读取weather_city.db数据库来查询cityID,这篇文章写怎么读取assets目录下的db文件,其实方法也挺简单的就是把assets目录下的db文件复制一份到"/data/data/" + packName + "/&

  • java读取resource目录下文件的方法示例

    本文主要介绍的是java读取resource目录下文件的方法,比如这是你的src目录的结构 ├── main │ ├── java │ │ └── com │ │ └── test │ │ └── core │ │ ├── bean │ │ ├── Test.java │ └── resources │ └── test │ ├── test.txt └── test └── java 我们希望在Test.java中读取test.txt文件中的内容,那么我们可以借助Guava库的Resource

  • java递归读取目录下所有文件的方法

    java递归读取目录下的所有文件(包含子目录下的所有文件)大概思路如下:通过file.listFiles()方法获取目录下的所有文件(包含子目录下的所有文件),得到files[]数组,然后遍历得到的所有文件,通过isFile(文件)和isDirectory(文件夹)方法来判断读取的是文件还是文件夹,如果得到的是文件夹,就递归调用test()方法,如果得到的是文件,就将其加入fileList中,最后测试的时候遍历fileList下的所有文件,来验证读取数据的准确性. package com.cha

  • Maven项目中读取src/main/resources目录下的配置文件的方法

    在Maven项目的开发中,当需要读取src/下的配置文件时,该怎么做? 我们假设Resources下有一个文件名为kafka.properties的配置文件(为什么用kafka.properties,因为这是在做kafka项目的时候碰到的问题,在网上查到了不少信息,索性当个搬运工,再根据自己的理解整理一下) 1.在java类中读取 若配置文件不在src/main/resources目录下,可以直接使用 Properties prop = new properties(); prop.load(n

  • Spring Boot读取resources目录文件方法详解

    这篇文章主要介绍了Spring Boot读取resources目录文件方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在Java编码过程中,我们常常希望读取项目内的配置文件,按照Maven的习惯,这些文件一般放在项目的src/main/resources下,因此,合同协议PDF模板.Excel格式的统计报表等模板的存放位置是resources/template/test.pdf,下面提供两种读取方式,它们分别在windows和Linux

  • python打包压缩、读取指定目录下的指定类型文件

    下面通过代码给大家介绍python打包压缩指定目录下的指定类型文件,具体代码如下所示: import os import datetime import tarfile import fnmatch def find_spe_file(root, patterns=['*'], non_cludedir=[]): for root, dirnames, filenames in os.walk(root): for pattern in patterns: for filename in fil

随机推荐