简体   繁体   中英

Jar null point exception when reading a file

The following code works fine on my Eclipse IDE.

private void getLayersAndDisplay() throws Exception {
        URL imageURL = ImageLab.class.getResource("earthlights.jpg");
        File imageFile = new File(imageURL.toURI());
        URL shapeFileURL = ImageLab.class.getResource("countries.shp");
        File shapeFile = new File(shapeFileURL.toURI());
        URL shapeFileURL2 = ImageLab.class.getResource("Brasil.shp");
        File shapeFile2 = new File(shapeFileURL2.toURI());
        displayLayers(imageFile, shapeFile,shapeFile2);
    }

However, when compiling to a jar, it gives me a null pointer exception. I thought that since I am getting it as a class.getResource, it would work. Can't I use the File class in a jar? Not even in a cast?

Thank you

An entry of a zip file (that's what a jar file is) is not a file existing in your file system. So you can't use a File, which represents a path on your filesystem, to refer to a zip entry. And you can't use file IO to read its content, since it's not a file.

I have no idea what you want to do, but if you want to read the content of the jar resource, just use ImageLab.class.getResourceAsStream() to get an InputStream back, reading from the entry.

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