Maven项目获取资源文件路径并读取资源文件内容

使用IDEA新建一个Maven项目

Maven项目获取资源文件路径并读取资源文件内容

demo/
    src/
        main/
            java/
            resources/   # 资源路径
    target/
        classes/         # 编译后文件

resources文件夹下的文件在编译后,都放在了根目录classes之下

一、获取项目路径

package com.demo;
import java.net.URL;
public class App {
    public static void main(String[] args) {
        //项目根路径
        URL url1 = App.class.getClassLoader().getResource("");
        System.out.println(url1.getPath());
        // 项目根路径
        URL url2 = App.class.getResource("/");
        System.out.println(url2.getPath());
        // 文件根路径
        URL url3 = App.class.getResource("");
        System.out.println(url3.getPath());
    }
}

输出结果(省略/demo前的路径,只看后面的路径)

package com.demo;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
public class App {
    public static void main(String[] args) throws IOException {
        URL url = App.class.getResource("/name.txt");
        String filename = url.getPath();
        System.out.println(filename);
        // /demo/target/classes/name.txt
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        String  line ;
        while ((line = reader.readLine())!= null){
            System.out.println(line);
        }
        reader.close();
    }
}
/demo/target/classes/
/demo/target/classes/
/demo/target/classes/com/demo/package com.demo;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
public class App {
    public static void main(String[] args) throws IOException {
        URL url = App.class.getResource("/name.txt");
        String filename = url.getPath();
        System.out.println(filename);
        // /demo/target/classes/name.txt
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        String  line ;
        while ((line = reader.readLine())!= null){
            System.out.println(line);
        }
        reader.close();
    }
}

二、读取文件

/demo/src/main/resources/name.txt

Tom
Jack
Jobs

读取文件内容

package com.demo;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
public class App {
    public static void main(String[] args) throws IOException {
        URL url = App.class.getResource("/name.txt");
        String filename = url.getPath();
        System.out.println(filename);
        // /demo/target/classes/name.txt
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        String  line ;
        while ((line = reader.readLine())!= null){
            System.out.println(line);
        }
        reader.close();
    }
}

输出结果

Tom
Jack
Jobs
• 1
• 2
• 3

参考

Maven获取resources的文件路径、读取resources的文件