How to get a path to a resource in a Java JAR file

前端 未结 16 2303
时光说笑
时光说笑 2020-11-22 09:23

I am trying to get a path to a Resource but I have had no luck.

This works (both in IDE and with the JAR) but this way I can\'t get a path to a file, only the file

16条回答
  •  悲&欢浪女
    2020-11-22 09:59

    I spent a while messing around with this problem, because no solution I found actually worked, strangely enough! The working directory is frequently not the directory of the JAR, especially if a JAR (or any program, for that matter) is run from the Start Menu under Windows. So here is what I did, and it works for .class files run from outside a JAR just as well as it works for a JAR. (I only tested it under Windows 7.)

    try {
        //Attempt to get the path of the actual JAR file, because the working directory is frequently not where the file is.
        //Example: file:/D:/all/Java/TitanWaterworks/TitanWaterworks-en.jar!/TitanWaterworks.class
        //Another example: /D:/all/Java/TitanWaterworks/TitanWaterworks.class
        PROGRAM_DIRECTORY = getClass().getClassLoader().getResource("TitanWaterworks.class").getPath(); // Gets the path of the class or jar.
    
        //Find the last ! and cut it off at that location. If this isn't being run from a jar, there is no !, so it'll cause an exception, which is fine.
        try {
            PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(0, PROGRAM_DIRECTORY.lastIndexOf('!'));
        } catch (Exception e) { }
    
        //Find the last / and cut it off at that location.
        PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(0, PROGRAM_DIRECTORY.lastIndexOf('/') + 1);
        //If it starts with /, cut it off.
        if (PROGRAM_DIRECTORY.startsWith("/")) PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(1, PROGRAM_DIRECTORY.length());
        //If it starts with file:/, cut that off, too.
        if (PROGRAM_DIRECTORY.startsWith("file:/")) PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(6, PROGRAM_DIRECTORY.length());
    } catch (Exception e) {
        PROGRAM_DIRECTORY = ""; //Current working directory instead.
    }
    

提交回复
热议问题