多种情况下jar包获取文件的路径,读取文件
多种情况下jar包获取文件的路径代码一、idea运行情况二、jar包运行情况三、总结代码代码中,分别使用AppMain.class.getResourceAppMain.class.getClassLoader().getResourcenew FileSystem.getProperty来获取路径其中resources文件夹还有一个a.json文件,模拟我们需要读取的资源p...
多种情况下jar包获取文件的路径
前言
java中说到获取文件路径, 获取文件, 读取配置, 有好几种方式, 但是每种方式获取到的结果都不太一样, 适用的场景也不太一样,jar中执行和idea中直接跑又不一样。相信很多人也和我一样想搞清楚, 这里就直接摆上demo和结果来看看。
项目的目录结构如下:
项目路径是D:\nowork\workspace\my-demo\demo-file (my-demo是主项目,demo-file是子模块)
代码
代码中,分别使用
- AppMain.class.getResource
- AppMain.class.getClassLoader().getResource
- new File
- System.getProperty
来获取路径
其中resources文件夹还有一个a.json文件,模拟我们需要读取的资源
package com.zgd.demo.file.path;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
/**
* AppMain
*
* @author zgd
* @date 2020/2/18 15:03
*/
public class AppMain {
public static void main(String[] args) throws MalformedURLException {
System.out.println("---------getResource---------");
//获取当前文件所在的路径
URL u1 = AppMain.class.getResource("");
//获取当前文件所在的路径
URL u2 = AppMain.class.getResource("a.json");
//获取项目根目录
URL u3 = AppMain.class.getResource("/");
URL u4 = AppMain.class.getResource("./a.json");
URL u5 = AppMain.class.getResource("/a.json");
System.out.println("AppMain.class.getResource(\"\").getPath() = " + (u1 == null ? "NullPointerException" : u1.getPath()));
System.out.println("AppMain.class.getResource(\"a.json\").getPath() = " + (u2 == null ? "NullPointerException" : u2.getPath()));
System.out.println("AppMain.class.getResource(\"/\").getPath() = " + (u3 == null ? "NullPointerException" : u3.getPath()));
System.out.println("AppMain.class.getResource(\"./a.json\").getPath() = " + (u4 == null ? "NullPointerException" : u4.getPath()));
System.out.println("AppMain.class.getResource(\"/a.json\").getPath() = " + (u5 == null ? "NullPointerException" : u5.getPath()));
System.out.println("\n---------getClassLoader---------");
String cl = Optional.ofNullable(AppMain.class.getClassLoader().getResource("")).orElse(new URL("file://NullPointerException")).getPath();
String cl2 = Optional.ofNullable(AppMain.class.getClassLoader().getResource("a.json")).orElse(new URL("file://NullPointerException")).getPath();
String cl3 = Optional.ofNullable(AppMain.class.getClassLoader().getResource("./a.json")).orElse(new URL("file://NullPointerException")).getPath();
String cl4 = Optional.ofNullable(AppMain.class.getClassLoader().getResource("/")).orElse(new URL("file://NullPointerException")).getPath();
System.out.println("AppMain.class.getClassLoader().getResource(\"\").getPath() = " + (cl == null ? "NullPointerException" : cl));
System.out.println("AppMain.class.getClassLoader().getResource(\"a.json\").getPath() = " + (cl2 == null ? "NullPointerException" : cl2));
System.out.println("AppMain.class.getClassLoader().getResource(\"./a.json\").getPath() = " + (cl3 == null ? "NullPointerException" : cl3));
System.out.println("AppMain.class.getClassLoader().getResource(\"/\").getPath() = " + (cl4 == null ? "NullPointerException" : cl4));
System.out.println("\n---------getPath---------");
String f1 = new File("").getPath();
String f2 = new File("a.json").getPath();
String f3 = new File("./a.json").getPath();
String f4 = new File("/").getPath();
System.out.println("new File(\"\").getPath() = " + f1);
System.out.println("new File(\"a.json\").getPath() = " + f2);
System.out.println("new File(\"./a.json\").getPath() = " + f3);
System.out.println("new File(\"/\").getPath() = " + f4);
System.out.println("\n---------getAbsolutePath---------");
//当前工程的绝对路径
String absolutePath1 = new File("").getAbsolutePath();
String absolutePath2 = new File("a.json").getAbsolutePath();
String absolutePath3 = new File("./a.json").getAbsolutePath();
String absolutePath4 = new File("/").getAbsolutePath();
System.out.println("new File(\"\").getAbsolutePath() = " + absolutePath1);
System.out.println("new File(\"a.json\").getAbsolutePath() = " + absolutePath2);
System.out.println("new File(\"./a.json\").getAbsolutePath() = " + absolutePath3);
System.out.println("new File(\"/\").getAbsolutePath() = " + absolutePath4);
// 获取工程路径
System.out.println("\n---------user.dir---------");
String sp1 = System.getProperty("user.dir");
System.out.println("System.getProperty(\"user.dir\") = " + sp1);
System.out.println("\n---------getFile---------");
try {
FileInputStream fileInputStream = new FileInputStream(AppMain.class.getClassLoader().getResource("a.json").getPath());
if (fileInputStream != null){
System.out.println("AppMain.class.getClassLoader().getResource(\"a.json\")获取文件成功");
}else{
System.out.println("AppMain.class.getClassLoader().getResource(\"a.json\")未获取到文件");
}
} catch (Exception e) {
System.out.println("AppMain.class.getClassLoader().getResource(\"a.json\")获取文件失败 = " + e);
}
try {
InputStream fileInputStream = AppMain.class.getClassLoader().getResourceAsStream("a.json");
if (fileInputStream != null){
System.out.println("AppMain.class.getClassLoader().getResourceAsStream(\"a.json\")获取文件成功");
}else{
System.out.println("AppMain.class.getClassLoader().getResourceAsStream(\"a.json\")未获取到文件");
}
} catch (Exception e) {
System.out.println("AppMain.class.getClassLoader().getResourceAsStream(\"a.json\")获取文件失败 = " + e);
}
}
}
一、idea运行情况
"C:\Program Files\Java\jdk1.8.0_181\bin\java.exe" -Dvisualvm.id=75322443593900 -javaagent:C:\Users\Administrator\AppData\Local\JetBrains\Toolbox\apps\IDEA-U\ch-0\203.6682.168\lib\idea_rt.jar=64403:C:\Users\Administrator\AppData\Local\JetBrains\Toolbox\apps\IDEA-U\ch-0\203.6682.168\bin -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_181\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\rt.jar;D:\nowork\workspace\my-demo\demo-file\target\classes;D:\repository\net\oschina\zcx7878\fastdfs-client-java\1.27.0.0\fastdfs-client-java-1.27.0.0.jar;D:\repository\com\zgd\base\util-common\1.0.0\util-common-1.0.0.jar;D:\repository\org\apache\httpcomponents\httpclient\4.5.10\httpclient-4.5.10.jar;D:\repository\org\apache\httpcomponents\httpcore\4.4.12\httpcore-4.4.12.jar;D:\repository\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;D:\repository\com\squareup\okhttp3\okhttp\4.2.0\okhttp-4.2.0.jar;D:\repository\com\squareup\okio\okio\2.2.2\okio-2.2.2.jar;D:\repository\org\jetbrains\kotlin\kotlin-stdlib\1.3.50\kotlin-stdlib-1.3.50.jar;D:\repository\org\jetbrains\kotlin\kotlin-stdlib-common\1.3.50\kotlin-stdlib-common-1.3.50.jar;D:\repository\org\jetbrains\annotations\13.0\annotations-13.0.jar;D:\repository\com\google\zxing\core\3.4.0\core-3.4.0.jar;D:\repository\com\google\zxing\javase\3.4.0\javase-3.4.0.jar;D:\repository\com\beust\jcommander\1.72\jcommander-1.72.jar;D:\repository\com\github\jai-imageio\jai-imageio-core\1.4.0\jai-imageio-core-1.4.0.jar;D:\repository\org\springframework\spring-core\5.1.9.RELEASE\spring-core-5.1.9.RELEASE.jar;D:\repository\org\springframework\spring-jcl\5.1.9.RELEASE\spring-jcl-5.1.9.RELEASE.jar;D:\repository\io\jsonwebtoken\jjwt\0.9.1\jjwt-0.9.1.jar;D:\repository\com\fasterxml\jackson\core\jackson-databind\2.9.6\jackson-databind-2.9.6.jar;D:\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;D:\repository\com\fasterxml\jackson\core\jackson-core\2.9.6\jackson-core-2.9.6.jar;D:\repository\commons-codec\commons-codec\1.13\commons-codec-1.13.jar;D:\repository\redis\clients\jedis\3.1.0\jedis-3.1.0.jar;D:\repository\org\apache\commons\commons-pool2\2.6.2\commons-pool2-2.6.2.jar;D:\repository\com\google\code\gson\gson\2.8.6\gson-2.8.6.jar;D:\repository\org\jsoup\jsoup\1.12.1\jsoup-1.12.1.jar;D:\repository\org\testng\testng\7.0.0\testng-7.0.0.jar;D:\repository\cn\hutool\hutool-all\5.2.5\hutool-all-5.2.5.jar;D:\repository\com\google\guava\guava\28.1-jre\guava-28.1-jre.jar;D:\repository\com\google\guava\failureaccess\1.0.1\failureaccess-1.0.1.jar;D:\repository\com\google\guava\listenablefuture\9999.0-empty-to-avoid-conflict-with-guava\listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar;D:\repository\com\google\code\findbugs\jsr305\3.0.2\jsr305-3.0.2.jar;D:\repository\org\checkerframework\checker-qual\2.8.1\checker-qual-2.8.1.jar;D:\repository\com\google\errorprone\error_prone_annotations\2.3.2\error_prone_annotations-2.3.2.jar;D:\repository\com\google\j2objc\j2objc-annotations\1.3\j2objc-annotations-1.3.jar;D:\repository\org\codehaus\mojo\animal-sniffer-annotations\1.18\animal-sniffer-annotations-1.18.jar;D:\repository\com\zgd\base\log-common\1.0.0\log-common-1.0.0.jar;D:\repository\org\projectlombok\lombok\1.18.16\lombok-1.18.16.jar;D:\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;D:\repository\junit\junit\4.12\junit-4.12.jar;D:\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\repository\com\alibaba\fastjson\1.2.57\fastjson-1.2.57.jar;D:\repository\net\sf\trove4j\core\3.1.0\core-3.1.0.jar;D:\repository\org\apache\commons\commons-lang3\3.8.1\commons-lang3-3.8.1.jar;D:\repository\org\apache\commons\commons-collections4\4.1\commons-collections4-4.1.jar" com.zgd.demo.file.path.AppMain
---------getResource---------
AppMain.class.getResource("").getPath() = /D:/nowork/workspace/my-demo/demo-file/target/classes/com/zgd/demo/file/path/
AppMain.class.getResource("a.json").getPath() = NullPointerException
AppMain.class.getResource("/").getPath() = /D:/nowork/workspace/my-demo/demo-file/target/classes/
AppMain.class.getResource("./a.json").getPath() = NullPointerException
AppMain.class.getResource("/a.json").getPath() = /D:/nowork/workspace/my-demo/demo-file/target/classes/a.json
---------getClassLoader---------
AppMain.class.getClassLoader().getResource("").getPath() = /D:/nowork/workspace/my-demo/demo-file/target/classes/
AppMain.class.getClassLoader().getResource("a.json").getPath() = /D:/nowork/workspace/my-demo/demo-file/target/classes/a.json
AppMain.class.getClassLoader().getResource("./a.json").getPath() = /D:/nowork/workspace/my-demo/demo-file/target/classes/a.json
AppMain.class.getClassLoader().getResource("/").getPath() =
---------getPath---------
new File("").getPath() =
new File("a.json").getPath() = a.json
new File("./a.json").getPath() = .\a.json
new File("/").getPath() = \
---------getAbsolutePath---------
new File("").getAbsolutePath() = D:\nowork\workspace\my-demo
new File("a.json").getAbsolutePath() = D:\nowork\workspace\my-demo\a.json
new File("./a.json").getAbsolutePath() = D:\nowork\workspace\my-demo\.\a.json
new File("/").getAbsolutePath() = D:\
---------user.dir---------
System.getProperty("user.dir") = D:\nowork\workspace\my-demo
---------getFile---------
AppMain.class.getClassLoader().getResource("a.json")获取文件成功
AppMain.class.getClassLoader().getResourceAsStream("a.json")获取文件成功
可以看出,
- AppMain.class.getResource
当前class文件的target位置 - AppMain.class.getClassLoader().getResource
项目target位置 - new File
项目位置 - System.getProperty
项目位置
二、jar包运行情况
打成jar包
直接在targe目录下执行jar, jar包名demo-file-1.0-SNAPSHOT.jar
结果:
---------getResource---------
AppMain.class.getResource("").getPath() = file:/D:/nowork/workspace/my-demo/demo-file/target/demo-file-1.0-SNAPSHOT.jar!/com/zgd/demo/file/path/
AppMain.class.getResource("a.json").getPath() = NullPointerException
AppMain.class.getResource("/").getPath() = NullPointerException
AppMain.class.getResource("./a.json").getPath() = NullPointerException
AppMain.class.getResource("/a.json").getPath() = file:/D:/nowork/workspace/my-demo/demo-file/target/demo-file-1.0-SNAPSHOT.jar!/a.json
---------getClassLoader---------
AppMain.class.getClassLoader().getResource("").getPath() =
AppMain.class.getClassLoader().getResource("a.json").getPath() = file:/D:/nowork/workspace/my-demo/demo-file/target/demo-file-1.0-SNAPSHOT.jar!/a.json
AppMain.class.getClassLoader().getResource("./a.json").getPath() =
AppMain.class.getClassLoader().getResource("/").getPath() =
---------getPath---------
new File("").getPath() =
new File("a.json").getPath() = a.json
new File("./a.json").getPath() = .\a.json
new File("/").getPath() = \
---------getAbsolutePath---------
new File("").getAbsolutePath() = D:\nowork\workspace\my-demo\demo-file\target
new File("a.json").getAbsolutePath() = D:\nowork\workspace\my-demo\demo-file\target\a.json
new File("./a.json").getAbsolutePath() = D:\nowork\workspace\my-demo\demo-file\target\.\a.json
new File("/").getAbsolutePath() = D:\
---------user.dir---------
System.getProperty("user.dir") = D:\nowork\workspace\my-demo\demo-file\target
---------getFile---------
AppMain.class.getClassLoader().getResource("a.json")获取文件失败 = java.io.FileNotFoundException: file:\D:\nowork\workspace\my-demo\demo-file\target\demo-file-1.0-SNAPSHOT.jar!\a.json (文件名、目录名或卷标语法不正确。)
AppMain.class.getClassLoader().getResourceAsStream("a.json")获取文件成功
三、总结
-
AppMain.class.getResource
当前class文件的target位置 -
AppMain.class.getClassLoader().getResource
项目target位置 -
new File
项目位置 -
System.getProperty
项目位置 -
重点,jar中如果想要读取classes下的文件,只能使用
getResourceAsStream按流的方式读取。不能使用getResource -
可以看出,如果你是要获取resources文件夹下的文件,使用第二种方式
如果要获取某个文件,在项目根目录和src平齐的,可以使用三四方式
更多推荐

所有评论(0)