JAVA获得绝对路径

转载自:http://hi.baidu.com/kylind/blog/item/457793a5ae30a9ff9052ee3f.html 工程下文件 工程下文件获得绝对路径:FilePathUtil.getAbsolutePath("./11.txt");
WebRoot下文件获得绝对路径:FilePathUtil.getAbsolutePath("/11.txt");
ClassPath下文件获得绝对路径:FilePathUtil.getAbsolutePath("11.txt");
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;

/**
* 由相对路径获得 绝对路径、File、文件列表,此工具根据 ClassPath寻找路径 注意:本类不要加到jar包中,不然会失效
* 在Servlet中获得文件真实路径 string file_real_path=getServletContext().getRealPath("/1.swf");
*
* @author KyLinD 2009-4-28 http://hi.baidu.com/kylind
* @version 1.0
*/
public class FilePathUtil {
private FilePathUtil() {
}

/**
* 根据相对路径获得 File
*
* @param relativePath
* 工程下的以"./"开头,web下的以"/"开头,ClassPath下的直接相对路径
* @return File
*/
public static File getFileByRelativePath( String relativePath) {
return new File( getAbsolutePath( relativePath));
}

/**
* 根据相对路径获得绝对路径
*
* @param relativePath
* 工程下的以"./"开头,web下的以"/"开头,ClassPath下的直接相对路径
* @return 绝对路径字符串
*/
public static String getAbsolutePath( String relativePath) {
String result = null;
if ( null != relativePath) {
if ( relativePath . indexOf( "./") == 0) {
String workspacePath = new File( "" ). getAbsolutePath();
relativePath = relativePath . substring( 2);
if ( relativePath . length() > 0) {
relativePath = relativePath
. replace( '/' , File . separatorChar);
result = workspacePath + String . valueOf( File . separatorChar)
+ relativePath;
} else {
result = workspacePath;
}
} else if ( relativePath . indexOf( "/") == 0) {
String webRootPath = getAbsolutePathOfWebRoot();
if ( relativePath . length() > 0) {
relativePath = relativePath
. replace( '/' , File . separatorChar);
result = webRootPath + relativePath;
} else {
result = webRootPath;
}
} else {
String classPath = getAbsolutePathOfClassPath();
if ( relativePath . length() > 0) {
relativePath = relativePath
. replace( '/' , File . separatorChar);
result = classPath + File . separatorChar + relativePath;
} else {
result = classPath;
}
}
}
return result;
}

// 得到WebRoot目录的绝对地址
private static String getAbsolutePathOfWebRoot() {
String result = null;
result = getAbsolutePathOfClassPath();
result = result . replace( File . separatorChar + "WEB-INF"
+ File . separatorChar + "classes" , "");
return result;
}

// 得到ClassPath的绝对路径
private static String getAbsolutePathOfClassPath() {
String result = null;
try {
File file = new File( getURLOfClassPath (). toURI());
result = file . getAbsolutePath();
} catch ( URISyntaxException e) {
e . printStackTrace();
}
return result;
}

// 得到ClassPath的URL
private static URL getURLOfClassPath() {
return getClassLoader (). getResource( "");
}

// 得到类加载器
private static ClassLoader getClassLoader() {
return FilePathUtil . class . getClassLoader();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值