在程中我们常取一些资源的绝对径,下面给出一个简单方便的工具类来帮助我们轻松的找到我想的资源。(适用于CS/BS应用)
- package hxw.test;
- import java.io.File;
- import java.io.IOException;
- import java.net.URI;
- import java.net.URISyntaxException;
- public class RealPathUtil
- {
- public static String getPathByClass(Class<?> clazz) {
- String path = null;
- try
- {
- URI uri = clazz.getResource("").toURI();
- File f = new File(uri);
- path = f.getCanonicalPath();
- }
- catch (URISyntaxException e)
- {
- e.printStackTrace();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- return path;
- }
- public static String getFilePathByClass(Class<?> clazz, String relativePath) {
- String path = null;
- try
- {
- String classPath = getPathByClass(clazz);
- StringBuffer sb = new StringBuffer(classPath);
- sb.append(File.separator);
- sb.append(relativePath);
- File newFile = new File(sb.toString());
- path = newFile.getCanonicalPath();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- return path;
- }
- public static void main(String[] args)
- {
- String path1 = getPathByClass(RealPathUtil.class);
- System.out.println(path1);
- String path2 = getFilePathByClass(RealPathUtil.class, "../../../p_w_picpath/p_w_picpath01.gif");
- System.out.println(path2);
- }
- }