Eclipse插件开发中获得当前工程目录(一)

2014-11-24 02:38:37 · 作者: · 浏览: 1

1、在普通Java工程下使用以下代码就行:

view sourceprint 1 String currentDir=System.getProperty("user.dir");

2、但是,在插件开发中,以上代码得到的是Eclipse的安装目录,如果想得到我们的代码所在的目录,则需要

view sourceprint 01 import java.io.File;

02 import java.io.IOException;

03 import java.net.MalformedURLException;

04 import java.net.URL;

05 import java.security.CodeSource;

06 import java.security.ProtectionDomain;

07

08 public class GetPath {

09

10 public static String getPathFromClass(Class cls) throws IOException {

11 String path = null;

12 if (cls == null) {

13 throw new NullPointerException();

14 }

15 URL url = getClassLocationURL(cls);

16 if (url != null) {

17 path = url.getPath();

18 if ("jar".equalsIgnoreCase(url.getProtocol())) {

19 try {

20 path = new URL(path).getPath();

21 } catch (MalformedURLException e) {

22 }

23 int location = path.indexOf("!/");

24 if (location != -1) {

25 path = path.substring(0, location);

26 }

27 }

28 File file = new File(path);

29 path = file.getCanonicalPath();

30 }

31 return path;

32 }

33

34 private static URL getClassLocationURL(final Class cls) {

35 if (cls == null)

36 throw new IllegalArgumentException("null input: cls");

37 URL result = null;

38 final String clsAsResource = cls.getName().replace('.', '/')

39 .concat(".class");

40 final ProtectionDomain pd = cls.getProtectionDomain();

41 if (pd != null) {

42 final CodeSource cs = pd.getCodeSource();

43 if (cs != null)

44 result = cs.getLocation();

45 if (result != null) {

46 if ("file".equals(result.getProtocol())) {

47 try {

48 if (result.toExternalForm().endsWith(".jar")

49 || result.toExternalForm().endsWith(".zip"))

50 result = new URL("jar:"

51 .concat(result.toExternalForm())

52 .concat("!/").concat(clsAsResource));

53 else if (new File(result.getFile()).isDirectory())

54 result = new URL(result, clsAsResource);

55 } catch (MalformedURLException ignore) {

56 }

57 }

58 }

59 }

60 if (result == null) {

61 final ClassLoader clsLoader = cls.getClassLoader();

62 result = clsLoader != null clsLoader.getResource(clsAsResource)

63 : ClassLoader.getSystemResource(clsAsResource);

64 }

65 return result;

66 }

67 }

以上代码可以得到指定类的绝对地址,如果想得到工程地址,只要把后面的字符串剪掉。

3、下面的代码

view sourceprint 1 String packageName = this.getClass().getResource("").getPath();

2 packageName = packageName.replace("/", "\\");
可以得到所在类的地址,但是在插件开发中得到的并非是绝对地址。在插件开发中可以结合2和3的代码得到当前工程的绝对地址: view sourceprint 01 String packageName = th