简体   繁体   中英

ClassLoader.getResource keeps returning null for existing resource

I am trying to include a local database file in my Runnable Jar. The application is based on an exisiting open source project, in wich they had the file in the package together with the Class. Now I am moving the database file to a 'res' map I created in the root project folder. Editing the code to find the new path to the database file didn't work. This is the piece of code:

 private static String defaultDBFileLocation() {
        final URL geoDBFileURL = ClassLoader.getSystemClassLoader().getResource("res/GeoIP.dat");
//        final URL geoDBFileURL = GeoIPServiceImpl.class.getResource("GeoIP.dat");
        if (geoDBFileURL == null) {
            return null;
        }

        try {
            final URI geoDBFileURI = geoDBFileURL.toURI();
            if (!geoDBFileURI.getScheme().equals("file")) {
                // class file loaded not from plain directory on filesystem, e.g. from jar, network, etc.
                return null;
            }
            final File geoDBFile = new File(geoDBFileURI);
            return geoDBFile.getPath();
        } catch (URISyntaxException e) {
            return null;
        } catch (IllegalArgumentException e) {
            return null;
        }
    }

The commmented line is the way the original creators used to get the file. The line above it is my new way. This method keeps returning null at this line:

if (geoDBFileURL == null)

Does anyone know what I am doing wrong here? Thanks

您应该使用Thread.currentThread().getContextClassLoader()javadoc )代替系统类加载器,后者是“新ClassLoader实例的默认委派父级,通常是用于启动应用程序的类加载器”( 参考 )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM