欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

多種情況下jar包獲取文件的路徑,讀取文件方式

 更新時(shí)間:2024年11月19日 14:39:20   作者:zzzgd816  
文章介紹了在不同情況下(IDEA運(yùn)行和JAR包運(yùn)行)獲取文件路徑的方法,并總結(jié)了每種方式的適用場景

前言

java中說到獲取文件路徑, 獲取文件, 讀取配置, 有好幾種方式, 但是每種方式獲取到的結(jié)果都不太一樣, 適用的場景也不太一樣,jar中執(zhí)行和idea中直接跑又不一樣。

相信很多人也和我一樣想搞清楚, 這里就直接擺上demo和結(jié)果來看看。

項(xiàng)目的目錄結(jié)構(gòu)如下:

項(xiàng)目路徑是D:\nowork\workspace\my-demo\demo-file (my-demo是主項(xiàng)目,demo-file是子模塊)

代碼

代碼中,分別使用

  • AppMain.class.getResource
  • AppMain.class.getClassLoader().getResource
  • new File
  • System.getProperty
    來獲取路徑

其中resources文件夾還有一個(gè)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---------");
    //獲取當(dāng)前文件所在的路徑
    URL u1 = AppMain.class.getResource("");
    //獲取當(dāng)前文件所在的路徑
    URL u2 = AppMain.class.getResource("a.json");
    //獲取項(xiàng)目根目錄
    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---------");
    //當(dāng)前工程的絕對路徑
    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運(yùn)行情況

"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 當(dāng)前class文件的target位置
  • AppMain.class.getClassLoader().getResource 項(xiàng)目target位置
  • new File 項(xiàng)目位置
  • System.getProperty 項(xiàng)目位置

二、jar包運(yùn)行情況

打成jar包

直接在targe目錄下執(zhí)行jar, jar包名demo-file-1.0-SNAPSHOT.jar

結(jié)果:

---------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 (文件名、目錄名或卷標(biāo)語法不正確。)
AppMain.class.getClassLoader().getResourceAsStream("a.json")獲取文件成功

三、總結(jié)

  • AppMain.class.getResource 當(dāng)前class文件的target位置
  • AppMain.class.getClassLoader().getResource 項(xiàng)目target位置
  • new File 項(xiàng)目位置
  • System.getProperty 項(xiàng)目位置

重點(diǎn),jar中如果想要讀取classes下的文件,只能使用getResourceAsStream按流的方式讀取。不能使用getResource

可以看出,如果你是要獲取resources文件夾下的文件,使用第二種方式

如果要獲取某個(gè)文件,在項(xiàng)目根目錄和src平齊的,可以使用三四方式

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Spring整合Dubbo框架過程及原理解析

    Spring整合Dubbo框架過程及原理解析

    這篇文章主要介紹了Spring整合Dubbo框架過程及原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • Java8中Stream的使用方式

    Java8中Stream的使用方式

    這篇文章主要介紹了Java8中Stream的使用方式,文章通過Stream的創(chuàng)建展開詳細(xì)的介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-04-04
  • 解決spring項(xiàng)目找不到Aspect依賴注解的問題

    解決spring項(xiàng)目找不到Aspect依賴注解的問題

    這篇文章主要介紹了解決spring項(xiàng)目找不到Aspect依賴注解的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • MyBatis-plus使用lambda條件構(gòu)造器報(bào)錯(cuò)問題及解決

    MyBatis-plus使用lambda條件構(gòu)造器報(bào)錯(cuò)問題及解決

    這篇文章主要介紹了MyBatis-plus使用lambda條件構(gòu)造器報(bào)錯(cuò)問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • Spring?Boot深入排查?java.lang.ArrayStoreException異常

    Spring?Boot深入排查?java.lang.ArrayStoreException異常

    這篇文章介紹了Spring?Boot深入排查?java.lang.ArrayStoreException異常,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-12-12
  • SpringBoot整合Mybatis無法掃描xml文件的解決

    SpringBoot整合Mybatis無法掃描xml文件的解決

    這篇文章主要介紹了SpringBoot整合Mybatis無法掃描xml文件的解決操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • 使用MUI框架構(gòu)建App請求http接口實(shí)例代碼

    使用MUI框架構(gòu)建App請求http接口實(shí)例代碼

    下面小編就為大家分享一篇使用MUI框架構(gòu)建App請求http接口實(shí)例代碼,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-01-01
  • Java快速排序與歸并排序及基數(shù)排序圖解示例

    Java快速排序與歸并排序及基數(shù)排序圖解示例

    快速排序是基于二分的思想,對冒泡排序的一種改進(jìn)。主要思想是確立一個(gè)基數(shù),將小于基數(shù)的數(shù)放到基數(shù)左邊,大于基數(shù)的數(shù)字放到基數(shù)的右邊,然后在對這兩部分進(jìn)一步排序,從而實(shí)現(xiàn)對數(shù)組的排序
    2022-09-09
  • SpringBoot整合Groovy腳本實(shí)現(xiàn)動態(tài)編程詳解

    SpringBoot整合Groovy腳本實(shí)現(xiàn)動態(tài)編程詳解

    這篇文章主要為大家介紹了SpringBoot整合Groovy腳本實(shí)現(xiàn)動態(tài)編程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-09-09
  • @Controller、@RestController注解區(qū)別詳解

    @Controller、@RestController注解區(qū)別詳解

    這篇文章主要介紹了@Controller、@RestController注解區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10

最新評論