【Java开发记录】程序打成jar相关静态资源加载情况(五)

429 阅读3分钟

图片

【Java开发记录】

程序打成jar相关静态资源加载情况(五)

日常程序编写打包会出先一个就是静态资源打包到jar里面加载不了相关情况、项目加载文件路径情况:

主要是还是new File()进行文件的加载和读取:

相对路径 绝对路径加载内容:

大概jar示意图:

图片

程序class路径:

com.thelostworld.core.XXXXX_FileUpload

静态资源路径根目录下面:

cXDQEmI1.zip

一、this.getClass().getResource("")方式进行path加载

这个时候jar运行加载路径:

就是jar目录的根目录文件:

URL fileURL=this.getClass().getResource("cXDQEmI1.zip");
/Users/thelostworld/Documents/idea_program/thelostworld/target/thelostworld.jar!/cXDQEmI1.zip

读取到jar程序包的根路径:

图片

通过这个方式指定路径到jar包中的静态文件

二、System.getProperty("user.dir")+""方式进行path加载

这个是定位程序当前运行的path+这个方式建议加载外部的资源方便

/Users/thelostworld/Documents/idea_program/thelostworld/target/cXDQEmI1.zip

图片

不同的环境运行的地区系统当前的path:

/Users/thelostworld/Desktop/cXDQEmI1.zip

图片

三、通过项目绝对路径去进行文件加载(不建议这个,灵活性不好)-自己debug测试方便,打包后不能使用

项目绝对路径

new file("/Users/thelostworld/Documents/idea_program/thelostworld/src/main/resources/cXDQEmI1.zip")

项目相对

new file("src/main/resources/cXDQEmI1.zip")

类似上面的直接的项目路径(替换一个位置就不行了)

图片

也可通过当前类加载这路径:

CLASSPATH="/cXDQEmI1.zip"
 //当前类的绝对路径
class.getResource( "/").getFile()
输出结果:/Users/thelostworld/Documents/idea_program/thelostworld/
//指定CLASSPATH文件的绝对路径
class.getResource(CLASSPATH).getFile()
输出结果:/Users/thelostworld/Documents/idea_program/thelostworld/target/cXDQEmI1.zip

总结:目前测试好几种方式个人建议加载外部资源,资源可替换和内容方便修改

补充扩展

同时也查询一些其他的java获取的资源:

Java在WEB项目中获取文件路径

jsp中获得文件路径servlet中获得文件路径java中获得文件路径jsp中获得文件路径
1、根目录所对应的绝对路径:request.getRequestURI();
2、文件的绝对路径:application.getRealPath(request.getRequestURI())
3、当前web应用的绝对路径:application.getRealPath("/")
4、取得请求文件的上层目录:

newFile(application.getRealPath(request.getRequestURI())).getParent()
servlet中获得文件路径
1、根目录所对应的绝对路径:request.getServletPath()
2、文件的绝对路径:
request.getSession().getServletContext().getRealPath(request.getRequestURI())
3、当前web应用的绝对路径:servletConfig.getServletContext().getRealPath("/")

注:ServletContext对象获得几种方式:
javax.servlet.http.HttpSession.getServletContext()
javax.servlet.jsp.PageContext.getServletContext()
javax.servlet.ServletConfig.getServletContext()
java中获得文件路径
1、Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()
2、MyClass.class.getClassLoader().getResource("").toURI().getPath()
3、ClassLoader.getSystemResource("").toURI().getPath()
4、MyClass.class.getResource("").toURI().getPath()
5、MyClass.class.getResource("/").toURI().getPath()
6、newFile("/").getAbsolutePath().toURI().getPath()
7、System.getProperty("user.dir").toURI().getPath()

参考:

blog.csdn.net/weixin\_337…

zhidao.baidu.com/question/21…

注意:⚠️

免责声明:本站提供安全工具、程序(方法)可能带有攻击性,仅供安全研究与教学之用,风险自负!

如果本文内容侵权或者对贵公司业务或者其他有影响,请联系作者删除。

转载声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

订阅查看更多复现文章、学习笔记

thelostworld

安全路上,与你并肩前行!!!!

图片

图片