java 路径 工具类,java 绝对路径工具类

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

import java.io.File;

import java.io.IOException;

import java.net.URI;

import java.net.URISyntaxException;

/** *//**

* @author Maryang

* @version $Revision: 1.0 $

* 这个类提供了一些根据类的class文件位置来定位的方法。

*/

public class PathUtil {

/** *//**

* 获取一个Class的绝对路径

* @param clazz Class对象

* @return Class的绝对路径

*/

public static String getPathByClass(Class clazz){

String path = null;

try {

URI uri = clazz.getResource("").toURI();

File file = new File(uri);

path = file.getCanonicalPath();

} catch (URISyntaxException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return path;

}

/** *//**

* 获取一个文件相对于一个Class相对的绝对路径

* @param clazz Class对象

* @param relativePath Class对象的相对路径

* @return 文件绝对路径

*/

public static String getFilePathByClass(Class clazz,String relativePath){

String filePath = null;

String clazzPath = getPathByClass(clazz);

StringBuffer sbPath = new StringBuffer(clazzPath);

sbPath.append(File.separator);

sbPath.append(relativePath);

File file = new File(sbPath.toString());

try {

filePath = file.getCanonicalPath();

} catch (IOException e) {

e.printStackTrace();

}

return filePath;

}

public static void main(String[] args) {

try {

System.out.println(getPathByClass(PathUtil.class));

System.out.println(getFilePathByClass(PathUtil.class,"../../images/logo.gif"));

} catch (Exception

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值