Where does Java put resource files when I JAR my program?

前端 未结 3 500
一向
一向 2021-01-20 23:26

Been looking for this for the past 2 hours and can\'t find anything (I\'ve found solutions to the same problem but with images, not text files).

Pretty much, I made a pr

3条回答
  •  花落未央
    2021-01-20 23:50

    Get the location of your jar file

    Firstly create a folder(say myfolder) and put your files inside it

    Consider the following function

    public String path(String filename)
    {
    URL url1 = getClass().getResource("");
    String ur=url1.toString();
    ur=ur.substring(9);
    String truepath[]=ur.split("myjar.jar!");
    truepath[0]=truepath[0]+"myfolder/";
    truepath[0]=truepath[0].replaceAll("%20"," ");
    return truepath[0]+filename;
    }//This method will work on Windows and Linux as well.
    //You can alternatively use the following line to get the path of your jar file
    //classname.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    

    Suppose your jar file is in D:\Test\dist

    Then path() will return /D:/Test/dist/myfolder/filename

    Now you can place 'myfolder' inside the folder where your jar file is residing

    OR

    If you want to access some read-only file inside your jar you should copy it to one

    of your packages and can access it as

    yourClassname.getResource("/packagename/filename.txt");

提交回复
热议问题