码迷,mamicode.com
首页 > 编程语言 > 详细

java web中各种路径的问题

时间:2016-05-12 18:22:09      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

绝对路径:绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(URL和物理路径)例如:

C:xyz est.txt 代表了test.txt文件的绝对路径。http://www.sun.com/index.htm也代表了一个URL绝对路径。

相对路径:相对与某个基准目录的路径。包含Web的相对路径(HTML中的相对目录),例如:在

Servlet中,"/"代表Web应用的跟目录。和物理路径的相对表示。例如:"./" 代表当前目录,"../"代表上级目录。这种类似的表示,也是属于相对路径。

获取路径的方法

private static Properties p;

static {

p = new Properties();

try {

p.load(Thread.currentThread().getContextClassLoader()

.getResourceAsStream("config.properties"));

} catch (IOException e) {

throw new RuntimeException(e.getMessage());

}

}

String namePath = p.getProperty("filter.library.name");

if (namePath.contains("classpath:")) {

namePath = namePath.replace("classpath:",

getClass().getResource("/").getPath());

}

try {

File f = new File(namePath);

if (!f.exists()) {

throw new FileNotFoundException();

}

BufferedWriter output = new BufferedWriter(new OutputStreamWriter(

new FileOutputStream(f, true), "utf-8")); // true

// 代表不覆盖源文件内容

output.write("," + name);

output.close();

} catch (IOException e) {

e.printStackTrace();

}

}



发布项目后:

1:(spring)

使用Spring,就可以用一种比较优雅的方式来获取了。
web.xml中的<web-app>节点内加入:

   <context-param>  
        <param-name>webAppRootKey</param-name>   
        <param-value>tansungWeb.root</param-value>  
    </context-param>  
    <listener>   
        <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>   
    </listener>

然后在普通的Java类中(不是action中),就可以通过System.getProperty("tansungWeb.root")获取了web根目录了。
然后再拼凑路径的时候,最好不要直接使用/或者\,最好使用File.separatorChar

System.out.println(System.getProperty("tansungWeb.root"));

D:\software\apache-tomcat-7.0.53-windows-x64\apache-tomcat-7.0.53\webapps\wlzbs-filter\


2:

this.getClass().getClassLoader().getResource("/").getPath();

/D:/software/apache-tomcat-7.0.53-windows-x64/apache-tomcat-7.0.53/webapps/wlzbs-filter/WEB-INF/classes/


3:

this.getClass().getClassLoader().getResource("").getPath();不加/

D:/software/apache-tomcat-7.0.53-windows-x64/apache-tomcat-7.0.53/webapps/wlzbs-filter/WEB-INF/classes/org/ansj/library/


发布没有项目:

所提取的路径都是项目下的路径,上面的方法提取的路径就都不是那样子了。

java web中各种路径的问题

标签:

原文地址:http://blog.csdn.net/qq_32364027/article/details/51354607

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!