How to get resources path from an Eclipse plugin

故事扮演 提交于 2020-01-03 12:24:28

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/34923454/how-to-get-resources-path-from-an-eclipse-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!