java获取文件路径

本文介绍了一个Java类,该类提供了五种不同的方法来获取当前项目的各种路径,包括工作空间路径、当前目录路径、类加载器资源路径等。这些方法对于理解和操作Java应用程序中的文件路径非常有用。
import java.io.File;
import java.io.IOException;

/**
* 获取各种路径
* @author 乐毅
*/
public class CisForUrl {


/**
* @see D:\workspace\20100823\menggov2
* @return String
*/
public static String getUrlOne(){
File file = new File("");
String path = "";
try {
path = file.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}

/**
* @see D:\workspace\20100823\menggov2
* @return String
*/
public static String getUrlTwo(){
String path = System.getProperty("user.dir");
return path;
}

/**
* @see /D:/workspace/20100823/menggov2/WebRoot/WEB-INF/classes/
* @return String
*/
public static String getUrlThree(){
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
return path;
}

/**
* @see /D:/workspace/20100823/menggov2/WebRoot/WEB-INF/classes/com/chinaintersoft/menggo/util/llj/
* @return String
*/
public static String getUrlFour(){
String path = CisForUrl.class.getResource("").getPath();
return path;
}

/**
* @see D:/workspace/20100823/menggov2/WebRoot
* @return String
*/
public static String getUrlFive(String className){
String path = CisForUrl.class.getResource("").getPath();
int index = path.indexOf("WEB-INF");
if(index == -1){
index = path.indexOf("bin");
}
path = path.substring(0,index);
if(path.startsWith("jar")){
// 当class文件在jar文件中时,返回"jar:file:/F:/ ..."样的路径
path = path.substring(10);
}else if(path.startsWith("file")){
// 当class文件在class文件中时,返回"file:/F:/ ..."样的路径
path = path.substring(6);
}
if(path.endsWith("/"))path = path.substring(1,path.length()-1);//不包含最后的"/"
return path;
}

public static void main(String[] args) {
System.out.println(CisForUrl.getUrlOne());
System.out.println(CisForUrl.getUrlTwo());
System.out.println(CisForUrl.getUrlThree());
System.out.println(CisForUrl.getUrlFour());
//System.out.println(CisForUrl.getUrlOne());
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值