java目录

1. 在jsp文件或Servlet中,可以通过getServletContext().getRealPath("/")来获取项目根目录的绝对路径。

2. Java桌面程序中,可以通过(new File("")).getAbsolutePath()获取项目根目录(非Tomcat下)。

.3. 在Tomcat下运行的类中,(new File("")).getAbsolutePath()获得的路径是Tomcat安装路径下的bin文件夹下,将获得的路径字符串去掉最后的"bin"再添上"webapps\项目文件夹名"即可。

4.web工程

/**
* @Description 获取web项目的根目录, E:/WorkSpace/qyqt
* 可以在windows,linux下tomcat,weblogic以包方式正确执行
* @author YY
* @date 2011-10-29/下午09:36:47
*/
public static String getRealRootPath() {
String classPath = null;
try {
//toURI() 20% to 空格
classPath = ExcelUtil.class.getClassLoader().getResource("/").toURI().getPath();
} catch (URISyntaxException e) {

e.printStackTrace();
}

String rootPath = "";
//windows下
if("\".equals(File.separator)){
rootPath = classPath.substring(1,classPath.indexOf("/WEB-INF/classes"));
rootPath = rootPath.replace("/", "\");
}
//linux下
if("/".equals(File.separator)){
rootPath = classPath.substring(0,classPath.indexOf("/WEB-INF/classes"));
rootPath = rootPath.replace("\", "/");
}
return rootPath;
}

5。

ClassLoader cl = IphoneApnsTask.class.getClassLoader();
InputStream is = cl.getResourceAsStream("com/mybank/aaa/aa.pm");

packagemy;

import java.io.File;
import java.io.IOException;
import java.net.URL;

publicclassMyUrlDemo{


publicstaticvoid main(String[] args){
MyUrlDemo muDemo =newMyUrlDemo();
try{
muDemo.showURL();
}catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}

publicvoid showURL()throwsIOException{

// 第一种:获取类加载的根路径 D:gitdaotiedaotie argetclasses
File f =newFile(this.getClass().getResource("/").getPath());
System.out.println(f);

// 获取当前类的所在工程路径; 如果不加“/” 获取当前类的加载目录 D:gitdaotiedaotie argetclassesmy
File f2 =newFile(this.getClass().getResource("").getPath());
System.out.println(f2);

// 第二种:获取项目路径 D:gitdaotiedaotie
File directory =newFile("");// 参数为空
String courseFile = directory.getCanonicalPath();
System.out.println(courseFile);


// 第三种: file:/D:/git/daotie/daotie/target/classes/
URL xmlpath =this.getClass().getClassLoader().getResource("");
System.out.println(xmlpath);


// 第四种: D:gitdaotiedaotie
System.out.println(System.getProperty("user.dir"));
/*
* 结果: C:Documents and SettingsAdministratorworkspaceprojectName
* 获取当前工程路径
*/

// 第五种: 获取所有的类路径 包括jar包的路径
System.out.println(System.getProperty("java.class.path"));

}
}
原文地址:https://www.cnblogs.com/yangy608/p/3467802.html