java web中各种路径的问题

绝对路径:绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(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/


发布没有项目:

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鑫不列迭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值