java获取文件路径的方法

作者:风筝 | 创建时间: 2023-05-14
在java开发项目过程中,经常需要读取或写入某个文件,这个时候就需要先获取文件路径。下面就介绍几种java常用来获取文件路径的方法...
java获取文件路径的方法

操作方法

this.getClass().getResource(""),得到的是当前class文件的URI目录 file:/E:/work/datai/code_study/study-master/study-common-test/target/classes/cn/sw/study/common/test/ this.getClass().getResource("/"),得到的是当前的classpath路径 file:/E:/work/datai/code_study/study-master/study-common-test/target/classes/

this.getClass().getClassLoader().getResource(""),得到的是当前的classpath路径 file:/E:/work/datai/code_study/study-master/study-common-test/target/classes/ this.getClass().getClassLoader().getResource("1/a.txt"),得到的是指定文件的绝对路径 file:/E:/work/datai/code_study/study-master/study-common-test/target/classes/1/a.txt

Thread.currentThread().getContextClassLoader().getResource(""),得到的是当前的classpath路径 file:/E:/work/datai/code_study/study-master/study-common-test/target/classes/ Thread.currentThread().getContextClassLoader().getResource("1/a.txt"),得到的是指定文件的绝对路径 file:/E:/work/datai/code_study/study-master/study-common-test/target/classes/1/a.txt

ClassLoader.getSystemResource(""),得到的是当前的classpath路径 file:/E:/work/datai/code_study/study-master/study-common-test/target/classes/ ClassLoader.getSystemResource("1/a.txt"),得到的是指定文件的绝对路径 file:/E:/work/datai/code_study/study-master/study-common-test/target/classes/1/a.txt

web应用下获取web的路径方法 request.getServletPath() request.getServletContext().getContextPath() request.getServletContext().getRealPath("") request.getServletContext().getRealPath("log4j2.xml")

从打印结果中可以看到 request.getServletPath()获取的是contentPath之后的/test/index request.getServletContext().getContextPath()获取的web应用上下文路径 request.getServletContext().getRealPath("")获取的是webapps下面应用的绝对路径

温馨提示

读取和写入文件的时候,最好不用使用硬编码路径,使用上面的方法获取到的路径是会随项目发布不同环境,获取对应的路径
点击展开全文

更多推荐