Java 读取resources下的文件
文档来源
三种实现方式

pom.xml
<!-- commons-io io的工具包 -->
<dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.6</version>
 </dependency>
 <!--junit4 单元测试-->
 <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.12</version>
 </dependency>
1、通过ClassLoader读取文件
 /**
     * 通过ClassLoader读取文件
     */
    @Test
    public void loadPropertiesFile() throws IOException {
        Properties properties = new Properties();
        properties.load(this.getClass().getClassLoader().getResourceAsStream("application.properties"));
        System.out.println("端口号:" + properties.getProperty("server.port"));
    }

 2、getClassLoader获取在转成输入流
//加载资源文件
        ClassPathResource classPathResource = new ClassPathResource("excelfile/" + "07版.xlsx");
        //获取文件
        File file = classPathResource.getFile();
        //获取路径
        String path = classPathResource.getPath();
        System.out.println("path:" + path);
        System.out.println("file:" + file);
        //转成输入流
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);
        //获取文件流
        FileInputStream inputStream = new FileInputStream(file);

 3、ResourceUtils获取文件
/**
     * ResourceUtils获取文件
     */
    @Test
    public void loadFile02() throws IOException {
        //获取文件的URL
        File file = ResourceUtils.getFile("classpath:excelfile/03版.xls");
        System.out.println("文件:" + file);
        //转成string输入文本
        String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        System.out.println("内容:" + content);
    }

Java读取resource文件/路径的几种方式
有时候想获取放在工程resources 文件下的文件路径,下面是几种方法:
String fileName = this.getClass().getClassLoader().getResource(“文件名”).getPath();//获取文件路径
 String fileUtl = this.getClass().getResource(“文件名”).getFile();
示例路径结果:/E:/idea_work/sofn-qry-web/target/classes/CityJson.js
File directory = new File(“”);//参数为空
 String courseFile = directory.getCanonicalPath()//标准的路径 ;
 String author =directory.getAbsolutePath()//绝对路径;



















