user3355101
user3355101

Reputation: 231

How to get resources path from an Eclipse plugin

I am developing an Eclipse plugin using Eclipse Plugin-in-project where it will add a menu item in the toolbar.

My plugin project is depending on one file which is located in the same plugin project I want the path of that file.

Below is the sample code I have used to get the path:

Bundle bundle = Platform.getBundle("com.feat.eclipse.plugin");
URL fileURL = bundle.getEntry("webspy/lib/file.txt");
File file = null;
String path=null;
try {
    file = new File(FileLocator.resolve(fileURL).toURI());
    path = file.getAbsolutePath();
} catch (URISyntaxException e1) {
    e1.printStackTrace();
} catch (IOException e1) {
    e1.printStackTrace();
}

While running from Eclipse Run as > Eclipse Application it is giving me the correct path. But when I export my plugin as jar and add it in my Eclipse plugins folder its not giving me the correct path.

Please help me to resolve this!

Upvotes: 7

Views: 3242

Answers (2)

greg-449
greg-449

Reputation: 111142

Use:

URL url = FileLocator.find(bundle, new Path("webspy/lib/file.txt"), null);

url = FileLocator.toFileURL(url);

File file = URIUtil.toFile(URIUtil.toURI(url));

When your files are packed in a jar FileLocator.toFileURL will copy them to a temporary location so that you can access them using File.

Upvotes: 6

Jonah Graham
Jonah Graham

Reputation: 7970

Files in jars have no java.io.File as they are in the JAR file.

You probably want FileLocator.openStream(...) to read the file contents.

If you really want a java.io.File, then you can consider using Eclipse EFS and its IFileStore.toLocalFile(...) to extract the file for you to a temporary directory. Something like EFS.getStore(fileURL).toLocalFile(EFS.CACHE, null) should do what you want, but remember that will put the file in the temp directory and delete it on Eclipse exit.

Upvotes: 0

Related Questions