应用绝对路径与相对路径

来源:这里教程网 时间:2026-02-21 13:06:37 作者:

这个问题就得看你的配置文件放在哪里啦,如果放在了项目的classes目录(或子目录)下,你可以用**.class.getresource('相对路径')来获取配置文件路径.如果是其他目录,那你只能在项目启动时通过servletcontext获取项目根目录+配置文件的目录来确定路径.并把路径放到类文件可以引用的地方啦. 
以下是我在做项目时写的一个用于获取路径的类,写的可能不太好.但还是希望能对你有所帮助: 
package com.example.web; 

import java.io.file; 
import java.net.url; 

import javax.servlet.servletcontext; 
import javax.servlet.http.httpservletrequest; 

/** 
* 路径获取类 
* */ 
public class webpath { 
/** 
  * 获取项目根目录的绝对路径 
  * 
  * @return 如:f:\tongjianpeng\j2eeutil 
  * */ 
public static string getabsolutepathwithproject() { 
  return system.getproperty("user.dir"); 


/** 
  * 获取项目所在盘符 
  * */ 
public static string getdriverpathwithproject() { 
  return new file("/").getabsolutepath(); 


/** 
  * 获取项目根目录的绝对路径 
  * 
  * @return 项目根目.例如
f:\tomcat\webapps\j2eeutil\ 
  * */ 
public static string getabsolutepathwithwebproject( 
   httpservletrequest request) { 
  return request.getsession().getservletcontext().getrealpath("/"); 


/** 
  * 获取项目根目录下的指定目录的绝对路径 
  * 
  * @param 项目根目下的指定目录 
  *            .例如:/login/ 
  * @return 项目根目下的指定目录.例如:
f:\tomcat\webapps\j2eeutil\login\ 
  * */ 
public static string getabsolutepathwithwebproject( 
   httpservletrequest request, string path) { 
  return request.getsession().getservletcontext().getrealpath(path); 


/** 
  * 获取项目根目录的绝对路径 
  * 
  * @return 项目根目.例如
f:\tomcat\webapps\j2eeutil\ 
  * */ 
public static string getabsolutepathwithwebproject(servletcontext context) { 
  return context.getrealpath("/"); 


/** 
  * 获取项目根目录下的指定目录的绝对路径 
  * 
  * @param 项目根目下的指定目录 
  *            .例如:/login/ 
  * @return 项目根目下的指定目录.例如:
f:\tomcat\webapps\j2eeutil\login\ 
  * */ 
public static string getabsolutepathwithwebproject(servletcontext context, 
   string path) { 
  return context.getrealpath(path); 


/** 
  * 获取项目classpath目录的绝对路径 
  * 
  * @return classes目录的绝对路径
 
  *         file:/f:/tomcat/webapps/j2eeutil/web-inf/classes/ 
  * */ 
public static url getabsolutepathwithclass() { 
  return webpath.class.getresource("/"); 


/** 
  * 获取项目classpath目录下的指定目录的绝对路径 
  * 
  * @param path 
  *            classes目录下的指定目录.比如:/com/ 
  * @return file:/f:/tomcat/webapps/j2eeutil/web-inf/classes/com/ 
  * */ 
public static url getabsolutepathwithclass(string path) { 
  return webpath.class.getresource(path); 


/** 
  * 获取指定类文件的所在目录的绝对路径 
  * 
  * @param clazz 
  *            类 
  * @return 类文件的绝对路径.例如:
包com.aries.util.web下的main.java类.
 
  *         路径为:file:/ 
  *         f:/tomcat/webapps/j2eeutil/web-inf/classes/com/aries/util/web/ 
  * */ 
public static url getabsolutepathwithclass(class clazz) { 
  return clazz.getresource(""); 

}

相关推荐