这个问题就得看你的配置文件放在哪里啦,如果放在了项目的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("");
}
}
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号