[ACCEPTED]-How do I access a file inside an OSGi bundle?-file-access

Accepted answer
Score: 16

Since the file is inside your bundle, there is 16 no way for you to get to it using a standard 15 File. The URL you get from Bundle.getResource() is the correct way 14 to get to these resources, since the OSGi 13 APIs are intended to also work on systems 12 without an actual file system. I would always 11 try to stick to the OSGi API instead of 10 using framework-specific solutions.

So, if 9 you have control over the method, I would 8 update it to take a URL, or maybe even an InputStream (since 7 you probably just want to read from it). For 6 convenience, you can always provide a helper 5 method that does take a File.

If you don't have control 4 over the method, you will have to write 3 some helper method that takes the URL, streams 2 it out to a file (for instance, File.createTempFile() will probably 1 do the trick.

Score: 7

Maybe the API is confusable, but You can 7 access a file inside an OSGI bundle like 6 this:

URL url = context.getBundle().getResource("com/my/weager/impl/test.txt");

// The url maybe like this: bundle://2.0:2/com/my/weager/impl/test.txt
// But this url is not a real file path :(, you could't use it as a file.
// This url should be handled by the specific URLHandlersBundleStreamHandler, 
// you can look up details in BundleRevisionImpl.createURL(int port, String path)
System.out.println(url.toString());

BufferedReader br =new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
while(br.ready()){
    System.out.println(br.readLine());
}
br.close();

getResource will find the resource through the 5 whole OSGI container just like OSGI classloader 4 theory.
getEntry will find the resource from local 3 bundle. and the return url could be convert 2 to file but inputStream.
Here is a question 1 same with this: No access to Bundle Resource/File (OSGi) Hope this helping you.

Score: 1

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

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

This 3 way the file will be loaded from your resource 2 dir. FileName should contain the path after 1 "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();
        }
    }
}

More Related questions