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

前端 未结 16 2113
时光说笑
时光说笑 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:48

    When loading a resource make sure you notice the difference between:

    getClass().getClassLoader().getResource("com/myorg/foo.jpg") //relative path
    

    and

    getClass().getResource("/com/myorg/foo.jpg")); //note the slash at the beginning
    

    I guess, this confusion is causing most of problems when loading a resource.


    Also, when you're loading an image it's easier to use getResourceAsStream():

    BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/com/myorg/foo.jpg"));
    

    When you really have to load a (non-image) file from a JAR archive, you might try this:

    File file = null;
    String resource = "/com/myorg/foo.xml";
    URL res = getClass().getResource(resource);
    if (res.getProtocol().equals("jar")) {
        try {
            InputStream input = getClass().getResourceAsStream(resource);
            file = File.createTempFile("tempfile", ".tmp");
            OutputStream out = new FileOutputStream(file);
            int read;
            byte[] bytes = new byte[1024];
    
            while ((read = input.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.close();
            file.deleteOnExit();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    } else {
        //this will probably work in your IDE, but not from a JAR
        file = new File(res.getFile());
    }
    
    if (file != null && !file.exists()) {
        throw new RuntimeException("Error: File " + file + " not found!");
    }
    

提交回复
热议问题