reading xml file inside a jar-package

后端 未结 4 578
悲哀的现实
悲哀的现实 2020-12-06 19:10

Here\'s my structure:

  • com/mycompany/ValueReader.class
  • com/mycompany/resources/values.xml

I can read the file in my Eclipse project, but

相关标签:
4条回答
  • 2020-12-06 19:46

    You can extract the jar then take what you want, in the same class-path using :

        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new   
    FileInputStream(zipfile.getCanonicalFile())));
    
    0 讨论(0)
  • 2020-12-06 19:56

    You can't get a File for the file because it's in a jar file. But you can get an input stream:

    InputStream in = ValueReader.class.getResourceAsStream("resources/values.xml");
    

    getResourceAsStream and getResource convert the package of the class to a file path, then add on the argument. This will give a stream for the file at path /com/mycompany/resources/values.xml.

    0 讨论(0)
  • 2020-12-06 20:03

    You can't get a File object (since it's no longer a file once it's in the .jar), but you should be able to get it as a stream via getResourceAsStream(path);, where path is the complete path to your class.

    e.g.

    /com/mycompany/resources/values.xml
    
    0 讨论(0)
  • 2020-12-06 20:07

    This will work...

    Thread.currentThread().getContextClassLoader().getResource("com/mycompany/resources/values.xml")
    
    0 讨论(0)
提交回复
热议问题