在程中我们常取一些资源的绝对径,下面给出一个简单方便的工具类来帮助我们轻松的找到我想的资源。(适用于CS/BS应用)
 

 

 
  
  1. package hxw.test;  
  2.  
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.net.URI;  
  6. import java.net.URISyntaxException;  
  7.  
  8. public class RealPathUtil  
  9. {  
  10.     public static String getPathByClass(Class<?> clazz) {  
  11.         String path = null;  
  12.           
  13.         try 
  14.         {  
  15.             URI uri = clazz.getResource("").toURI();  
  16.             File f = new File(uri);  
  17.             path = f.getCanonicalPath();  
  18.         }  
  19.         catch (URISyntaxException e)  
  20.         {  
  21.             e.printStackTrace();  
  22.         }  
  23.         catch (IOException e)  
  24.         {  
  25.             e.printStackTrace();  
  26.         }  
  27.           
  28.         return path;  
  29.     }  
  30.       
  31.     public static String getFilePathByClass(Class<?> clazz, String relativePath) {  
  32.         String path = null;  
  33.           
  34.         try 
  35.         {  
  36.             String classPath = getPathByClass(clazz);   
  37.             StringBuffer sb = new StringBuffer(classPath);  
  38.             sb.append(File.separator);  
  39.             sb.append(relativePath);  
  40.               
  41.             File newFile = new File(sb.toString());  
  42.             path = newFile.getCanonicalPath();  
  43.         }  
  44.         catch (IOException e)  
  45.         {  
  46.             e.printStackTrace();  
  47.         }  
  48.           
  49.         return path;  
  50.     }  
  51.       
  52.     public static void main(String[] args)  
  53.     {  
  54.         String path1 = getPathByClass(RealPathUtil.class);  
  55.         System.out.println(path1);  
  56.         String path2 = getFilePathByClass(RealPathUtil.class"../../../p_w_picpath/p_w_picpath01.gif");  
  57.         System.out.println(path2);  
  58.     }  
  59. }