linux与windows下获取web-inf目录或classespath的正确方法
在windows下获得web-inf目录,网上一大堆的例子
总结出来就是下面这句代码最合适:
pathfilenew = (Thread.currentThread().getContextClassLoader().getResource("").toString()).replace('/', '\\').replace("file:", "").replace("classes\\", "").substring(1).replace("%20", " ");说明一下:windows下通过下面的代码获得地址是file:/d:/abc/asd.txt,而windows是反斜杠,所以需要进行转换为反斜杠,下面看说明。
Thread.currentThread().getContextClassLoader().getResource("").toString()
查看上面的代码,我们需要做的是:
1,将/ 转换成\\,windows为反斜杠
2,将file:去掉
3,去掉classes\\,因为已经将\转换成了\\,所以这里是classes\\
4,去掉第一个符号
5,replace("%20", " ")是将%20转换成空格,因为在获取到的地址中如果有空格会被转换成%20,因此需要重新转换为空格
这样我们就完成了获得了我们项目下的web-inf目录
那么在linux下如何获得呢?
在linux下的文件和windows下的文件有一个显著的区别,那就是它的文件路劲使用的是正斜杠"/",其他都一样,因此,linux下获得web-inf目录的代码就应该是这个样子
pathfilenew = (Thread.currentThread().getContextClassLoader().getResource("").toString()).replace("file:", "").replace("classes/", "")
爆款云服务器s6 2核4G 低至0.46/天,具体规则查看活动详情