当前位置: 代码网 > it编程>游戏开发>ar > 多种情况下jar包获取文件的路径,读取文件方式

多种情况下jar包获取文件的路径,读取文件方式

2024年11月20日 ar 我要评论
前言java中说到获取文件路径, 获取文件, 读取配置, 有好几种方式, 但是每种方式获取到的结果都不太一样, 适用的场景也不太一样,jar中执行和idea中直接跑又不一样。相信很多人也和我一样想搞清

前言

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)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com