在class文件中读取Tomcat站点的根目录
来源:互联网 发布:http json 格式 编辑:程序博客网 时间:2024/09/21 09:04
在JSP开发中,我们有时需要在class文件中读取站点下的配制文件。这样的话,我们就要知道站点根目录的物理路径。在JSP文件中得到站点根目录的物理路径很容易,代码如下:
String rootPath = request.getRealPath(”/”);
但是,要在class文件中得到站点根目录,却没有这样简便的方法。
这两天,我也遇到了同样的问题。Google了一下,发现每个类下面都有一个class属性(也许是方法),class属性下有一个getResource方法。通过 getResource 方法能够查找带有给定名称的资源,代码如下:
String url = Test.class.getResource(”config.txt”).toString(); // Test为一个自定义类
如果没有找到资源,则 getResource 方法返回null。 假设Test类的包为”com.test”,资源也能找到,则在Tomcat项目中,url的值将为”$Webapp/WEB-INF/classes/com/test/config.txt”。如果代码如下:
String url = Test.class.getResource(”/config.txt”).toString();
则url的值将为”$Webapp/WEB-INF/classes/config.txt”。显然,getResource方法可能接受常规的相对路径。(经过检测,getResource方法不能接受物理路径,否则返回null)
通常情况下,一个JSP站点有且只有一个”WEB-INF”目录。而且,”WEB-INF”目录不可以嵌套。因此,我们可能通过查询”WEB-INF”字符串的位置,来截取站点的根目录。为了方便使用,我专门写了一个Application类来取得应用程序(在Tomcat中,即为JSP站点)的根目录。源代码如下:
package com.application;
public class Application {
private Application(){
}
public static Application getInstance(){
return new Application();
}
public String getRootPath(){
// 因为类名为”Application”,因此” Application.class”一定能找到
String result = Application.class.getResource(”Application.class”).toString();
int index = result.indexOf(”WEB-INF”);
if(index == -1){
index = result.indexOf(”bin”);
}
result = result.substring(0,index);
if(result.startsWith(”jar”)){
// 当class文件在jar文件中时,返回”jar:file:/F:/ …”样的路径
result = result.substring(10);
}else if(result.startsWith(”file”)){
// 当class文件在jar文件中时,返回”file:/F:/ …”样的路径
result = result.substring(6);
}
return result;
}
}
使用代码如下,取得站点根目录:
String rootPath = Application.getInstance().getRootPath();
- 在class文件中读取Tomcat站点的根目录
- 在class文件中读取Tomcat站点的根目录
- tomcat下建虚拟目录以及在tomcat首页页面中显示根目录下的文件列表
- tomcat下建虚拟目录以及在tomcat首页页面中显示根目录下的文件列表
- tomcat配置站点根目录
- class.getResource()的用法-----tomcat中的.class文件读取文件
- servlet在tomcat中读取文件问题
- Myeclipse中的使用javassist修改时class文件时生成的class文件在项目的根目录下。
- Tomcat根目录下各个文件的作用
- 在Windows中配置多个tomcat服务器和修改tomcat的根目录
- 在Tomcat中配置WEB站点的虚拟目录
- 相对于站点根目录的绝对路径
- 设置网站站点的根目录
- 获取站点根目录的方法
- 设置web站点的根目录
- PHP 站点根目录的获取
- 如何在tomcat服务器中读取xml文件(路径问题)
- Java从包中读取所有的class文件
- Android的生命周期
- Enterprise Library连接Access数据
- 1366 栈
- format 参数说明
- 1367 双堆栈练习
- 在class文件中读取Tomcat站点的根目录
- GBK UTF8 编码转换
- 【转】 J2EE应用高性能构建技巧_性能瓶颈
- 解决Netbeans 下 undefined reference to `pthread_create'
- GPIO口的设置
- 1368 表达式转换
- linux各文件夹的作用(转)
- linux shell 字符串操作(长度,查找,替换)详解
- zoj3516和树相关