How do I access a file inside an OSGi bundle?

前端 未结 3 1819
梦谈多话
梦谈多话 2021-02-19 01:19

I am new to OSGi and created an OSGi-bundle which I run in the Apache Felix OSGi-container. There is a file resource contained in the bundle, which I need to pass to a method as

3条回答
  •  故里飘歌
    2021-02-19 01:58

    What I use is getClassLoader().getResourceAsStream():

    InputStream inStream = new java.io.BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream(fileName));
    

    This way the file will be loaded from your resource dir. FileName should contain the path after "src/main/resources".

    Full example here:

    static public byte[] readFileAsBytes(Class c, String fileName) throws IOException {
        InputStream inStream = new java.io.BufferedInputStream(c.getClassLoader().getResourceAsStream(fileName));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int nbytes = 0;
        byte[] buffer = new byte[100000];
    
        try {
            while ((nbytes = inStream.read(buffer)) != -1) {
                out.write(buffer, 0, nbytes);
            }
            return out.toByteArray();
        } finally {
            if (inStream != null) { 
                inStream.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
    

提交回复
热议问题