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
10public static String getPathFromClass(Class cls) throws IOException {
11String path = null;
12if (cls == null) {
13throw new NullPointerException();
14}
15URL url = getClassLocationURL(cls);
16if (url != null) {
17path = url.getPath();
18if ("jar".equalsIgnoreCase(url.getProtocol())) {
19try {
20path = new URL(path).getPath();
21} catch (MalformedURLException e) {
22}
23int location = path.indexOf("!/");
24if (location != -1) {
25path = path.substring(0, location);
26}
27}
28File file = new File(path);
29path = file.getCanonicalPath();
30}
31return path;
32}
33
34private static URL getClassLocationURL(final Class cls) {
35if (cls == null)
36throw new IllegalArgumentException("null input: cls");
37URL result = null;
38final String clsAsResource = cls.getName().replace('.', '/')
39.concat(".class");
40final ProtectionDomain pd = cls.getProtectionDomain();
41if (pd != null) {
42final CodeSource cs = pd.getCodeSource();
43if (cs != null)
44result = cs.getLocation();
45if (result != null) {
46if ("file".equals(result.getProtocol())) {
47try {
48if (result.toExternalForm().endsWith(".jar")
49|| result.toExternalForm().endsWith(".zip"))
50result = new URL("jar:"
51.concat(result.toExternalForm())
52.concat("!/").concat(clsAsResource));
53else if (new File(result.getFile()).isDirectory())
54result = new URL(result, clsAsResource);
55} catch (MalformedURLException ignore) {
56}
57}
58}
59}
60if (result == null) {
61final ClassLoader clsLoader = cls.getClassLoader();
62result = clsLoader != null ? clsLoader.getResource(clsAsResource)
63: ClassLoader.getSystemResource(clsAsResource);
64}
65return result;
66}
67 }
以上代码可以得到指定类的绝对地址,如果想得到工程地址,只要把后面的字符串剪掉。
3、下面的代码
view sourceprint?1 String packageName = this.getClass().getResource("").getPath();
2 packageName = packageName.replace("/", "\\");
可以得到所在类的地址,但是在插件开发中得到的并非是绝对地址。在插件开发中可以结合2和3的代码得到当前工程的绝对地址: view sourceprint?01 String packageName = this.getClass().getResource("").getPath();
02 packageName = packageName.replace("/", "\\");
03 System.out.println("包名:"+packageName);
04 String projectPath = null;
05 try {
06String packageFullName = GetPath.getPathFromClass(this.getClass());
07projectPath = packageFullName.substring(0,
08packageFullName.indexOf(packageName) + 1);
09System.out.println("工程路径:"+projectPath);
10 } catch (IOException e1) {
11projectPath = null;
12e1.printStackTrace();
13 }
作者“双子座的博客”