转自:http://blog.csdn.net/hpf911/article/details/5852127
java获取当前项目路径:
- object.class.getResource()方法获得当前生成的class的绝对路径(此方法在jar包中无效,因为他获得的是生成的class的路径,返回的内容最后包含/)
-
- public static String getFilePath(String fileName)
- {
- String path = GetFilePath.class.getResource("").toString();
-
- if (path != null)
- {
- path = path.substring(5, path.indexOf("WEB-INF") + 8);
-
- }
- return (path + fileName);
- }
- getClass().getResource() 方法获得相对路径( 此方法在jar包中无效。返回的内容最后包含/)
例如 项目在/D:/workspace/MainStream/Test
在javaProject中,getClass().getResource("/").getFile().toString()
返回:/D:/workspace/MainStream/Test/bin/
- public String getCurrentPath(){
-
- String rootPath=getClass().getResource("/").getFile().toString();
-
- String currentPath1=getClass().getResource(".").getFile().toString();
- String currentPath2=getClass().getResource("").getFile().toString();
-
- String parentPath=getClass().getResource("../").getFile().toString();
-
- return rootPath;
-
- }
public String getCurrentPath(){
//取得根目录路径
String rootPath=getClass().getResource("/").getFile().toString();
//当前目录路径
String currentPath1=getClass().getResource(".").getFile().toString();
String currentPath2=getClass().getResource("").getFile().toString();
//当前目录的上级目录路径
String parentPath=getClass().getResource("../").getFile().toString();
return rootPath;
}
- 利用System.getProperty()函数获取当前路径,得到项目文件夹的根目录,不带/
例如 项目在
D:\workspace\testPorjject
者System.getProperty("user.dir")
返回 D:\workspace\testPorjject
- System.out.println(System.getProperty("user.dir"));
- File directory = new File("");
- try{
- System.out.println(directory.getCanonicalPath());
- System.out.println(directory.getAbsolutePath());
- }catch(Exceptin e){}
jsp中:
- request.getContextPath()
- request.getSession().getServletContext().getRealPath()
servlet中:
- this.getServletContext().getRealPath("/");
- this.getServlet().getServletContext().getRealPath("/");
java中获取当前路径(转)
原文:http://www.cnblogs.com/summer520/p/3559110.html