代码改变世界

[原]Eclipse RCP 程序获取程序路径

2011-11-04 21:28  hedalixin  阅读(656)  评论(0)    收藏  举报

一、Rcp程序获取程序安装路径

  1. String path = null;  
  2. Location location = Platform.getInstallLocation();  
  3. if (location != null) {  
  4.     URL url = location.getURL();  
  5.     path = url.getPath();  
  6. }  

 

二、获取Plug-in中的资源的绝对路径

  1. import java.io.IOException;  
  2. import java.net.MalformedURLException;  
  3. import java.net.URL;  
  4.   
  5. import org.eclipse.core.runtime.FileLocator;  
  6. import org.eclipse.core.runtime.Path;  
  7. import org.eclipse.core.runtime.Platform;  
  8. import org.osgi.framework.Bundle;  
  9.   
  10. public class TestGetFullPath {  
  11.         //filePath 为资源的相对路径  
  12.     public static String getFullPath(String pluginId, String filePath) {  
  13.         if (pluginId == null || filePath == null) {  
  14.             throw new IllegalArgumentException();  
  15.         }  
  16.   
  17.         // if the bundle is not ready then there is no file  
  18.         Bundle bundle = Platform.getBundle(pluginId);  
  19.         if (!isReady(bundle)) {  
  20.             return null;  
  21.         }  
  22.   
  23.         // look for the file (this will check both the plugin and fragment  
  24.         // folders  
  25.         URL fullPathString = find(bundle, filePath);  
  26.         if (fullPathString == null) {  
  27.             try {  
  28.                 fullPathString = new URL(filePath);  
  29.             } catch (MalformedURLException e) {  
  30.                 return null;  
  31.             }  
  32.         }  
  33.   
  34.         if (fullPathString == null) {  
  35.             return null;  
  36.         }  
  37.         try {  
  38.             fullPathString = FileLocator.toFileURL(fullPathString);  
  39.         } catch (IOException e) {  
  40.             e.printStackTrace();  
  41.         }  
  42.         return fullPathString.getPath();  
  43.     }  
  44.   
  45.     public static boolean isReady(Bundle bundle) {  
  46.         return bundle != null && isReady(bundle.getState());  
  47.     }  
  48.   
  49.     public static boolean isReady(int bundleState) {  
  50.         return (bundleState & (Bundle.RESOLVED | Bundle.STARTING  
  51.                 | Bundle.ACTIVE | Bundle.STOPPING)) != 0;  
  52.     }  
  53.       
  54.     public static URL find(Bundle bundle, String path) {  
  55.         if (bundle == null) {  
  56.             return null;  
  57.         }  
  58.         return FileLocator.find(bundle, new Path(path), null);  
  59.     }  
  60. }  

作者:salc3k 发表于2011-11-4 21:28:16 原文链接
阅读:89 评论:0 查看评论