多种情况下jar包获取文件的路径
代码
一、idea运行情况
二、jar包运行情况
三、总结
代码
代码中,分别使用
AppMain.class.getResource
AppMain.class.getClassLoader().getResource
new File
System.getProperty
来获取路径
其中resources文件夹还有一个a.json文件,模拟我们需要读取的资源
package com.zgd.demo.test.filepath;
import java.io.File;
import java.net.URL;
import java.nio.file.Path;
/**
* AppMain
*
* @author zgd
* @date 2020/2/18 15:03
*/
public class AppMain {
public static void main(String[] args) {
//获取当前文件所在的路径
URL localPath = AppMain.class.getResource("");
System.out.println("AppMain.class.getResource(\"\").getPath() = " + (localPath == null ? "NullPointerException" : localPath.getPath()));
//获取当前文件所在的路径
URL localPath2 = AppMain.class.getResource("a.json");
System.out.println("AppMain.class.getResource(\"a.json\").getPath() = " + (localPath2 == null ? "NullPointerException" : localPath2.getPath()));
//获取项目根目录
URL rootPath = AppMain.cl