eclipse插件开发获取Eclipse相关的文件根目录

时间:2023-02-07 08:35:59

最近在写一个eclipse插件,存储文件的时候就需要用到相关的文件路径,由于eclipse本身是一个跨操作系统的应用,所以我们不可以无脑的写c://path  之类的路径,最后还是使用相对eclipse路径的比较好,这样做的好处主要是以下三点

1统一管理//避免我们需要通过操作系统 以及用户习惯来制定相应的文件目录

2可以跨平台

3会规避掉一些读写权限的问题。//eclipse拥有worksapce下的读写权限,所以我们的插件也可以在该目录下读写


下面的内容是我基于http://www.neohope.com/2014/08/07/%25E8%258E%25B7%25E5%258F%2596eclipse%25E6%2589%25A7%25E8%25A1%258C%25E6%2596%2587%25E4%25BB%25B6%25E6%25A0%25B9%25E7%259B%25AE%25E5%25BD%2595/

的blog内容加上自己验证之后的结果


String eclipseRoot = Platform.getInstallLocation().getURL().toString();
eclipseRoot = eclipseRoot.replace("file:/", "");
System.out.println(eclipseRoot); // D:/eclipse/
//Eclipse插件获取Workspace根目录

//方法1
String workspaceRoot= Platform.getInstanceLocation().getURL().toString();
workspaceRoot = workspaceRoot.replace("file:/", "");
System.out.println(workspaceRoot);//D:/Workspaces/runtime-EclipseApplication/
//方法2
String path = Activator.getDefault().getStateLocation().makeAbsolute().toFile().getAbsolutePath();
System.out.println(path); //D:\Workspaces\runtime-EclipseApplication\.metadata\.plugins\com.xclenter.test
//Eclipse插件获取User根目录
String userHome = Platform.getUserLocation().getURL().toString();
userHome = userHome.replace("file:/", "");
System.out.println(userHome); //C:/Users/soft/user/

以上得到的4个路径分别是

1 eclipse安装位置

2 eclipse工作目录

3 eclipse工作目录下插件运行的上下文,主要存放的是插件运行的preference  log等文件

4 用户在系统的下的根目录


下面还有一个是暂时没有弄清楚的作用的路径,留作以后探讨吧

//Elclipse插件获取Bundle的OSGI路径
//方法1
String bundlePath = Activator.getDefault().getBundle().getLocation();
String pathBundle = bundlePath.replace("reference:file:/","");
System.out.println(pathBundle); //D:/Workspaces/Eclipse/com.xclenter.test/