How do I read a resource file from a Java jar file?

后端 未结 9 1594
遥遥无期
遥遥无期 2020-11-22 09:22

I\'m trying to access an XML file within a jar file, from a separate jar that\'s running as a desktop application. I can get the URL to the file I need, but when I pass tha

9条回答
  •  悲哀的现实
    2020-11-22 09:54

    I have 2 CSV files that I use to read data. The java program is exported as a runnable jar file. When you export it, you will figure out it doesn't export your resources with it.

    I added a folder under project called data in eclipse. In that folder i stored my csv files.

    When I need to reference those files I do it like this...

    private static final String ZIP_FILE_LOCATION_PRIMARY = "free-zipcode-database-Primary.csv";
    private static final String ZIP_FILE_LOCATION = "free-zipcode-database.csv";
    
    private static String getFileLocation(){
        String loc = new File("").getAbsolutePath() + File.separatorChar +
            "data" + File.separatorChar;
        if (usePrimaryZipCodesOnly()){              
            loc = loc.concat(ZIP_FILE_LOCATION_PRIMARY);
        } else {
            loc = loc.concat(ZIP_FILE_LOCATION);
        }
        return loc;
    }
    

    Then when you put the jar in a location so it can be ran via commandline, make sure that you add the data folder with the resources into the same location as the jar file.

提交回复
热议问题