Chinese To English     英文 转 中文             
         
随笔-27  评论-53  文章-0  trackbacks-0

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

 1import java.io.File;
 2import java.io.IOException;
 3import java.net.URI;
 4import java.net.URISyntaxException;
 5
 6/**
 7 * @author <a href="mailto:maryang@live.cn">Maryang</a>
 8 * @version $Revision: 1.0 $
 9 * 这个类提供了一些根据类的class文件位置来定位的方法。
10 */

11public class PathUtil {
12    
13    /**
14     * 获取一个Class的绝对路径
15     * @param clazz Class对象
16     * @return Class的绝对路径
17     */

18    public static String getPathByClass(Class clazz){
19        String path = null;
20        try {
21            URI uri = clazz.getResource("").toURI();
22            File file = new File(uri);
23            path = file.getCanonicalPath();
24        }
 catch (URISyntaxException e) {
25            e.printStackTrace();
26        }
 catch (IOException e) {
27            e.printStackTrace();
28        }

29        return path;
30    }

31    
32    /**
33     * 获取一个文件相对于一个Class相对的绝对路径
34     * @param clazz Class对象
35     * @param relativePath Class对象的相对路径
36     * @return 文件绝对路径
37     */

38    public static String getFilePathByClass(Class clazz,String relativePath){
39        String filePath = null;
40        String clazzPath = getPathByClass(clazz);
41        StringBuffer sbPath = new StringBuffer(clazzPath);
42        sbPath.append(File.separator);
43        sbPath.append(relativePath);
44        File file = new File(sbPath.toString());
45        try {
46            filePath = file.getCanonicalPath();
47        }
 catch (IOException e) {
48            e.printStackTrace();
49        }

50        return filePath;
51    }

52
53    public static void main(String[] args) {
54        try {
55            System.out.println(getPathByClass(PathUtil.class));
56            System.out.println(getFilePathByClass(PathUtil.class,"../../images/logo.gif"));
57        }
 catch (Exception e) {
58            e.printStackTrace();
59        }

60    }

61}


杰森 
邮箱:json.shen(at)gmail.com
网站:www.shenjia.org
posted on 2009-03-12 13:56 杰森 阅读(687) 评论(0)  编辑  收藏 所属分类: JavaSE

只有注册用户登录后才能发表评论。


网站导航:
 
嗨117