Java

Spring的资源访问

2020-03-06  本文已影响0人  愤怒的老照

路径访问方式

Spring可以通过classpathfilehttpftp没有前缀五种方式访问资源

区别

地址前缀 示例 对应的资源类型
classpath: classpath:/spring/spring-*.xml 从类路径中加载资源,classpath:和classpath:/是等价的,都是相对于类的根路径。资源文件库标准的在文件系统中,也可以在JAR或ZIP的类包中
file: file:/conf/bean.xml 使用UrlResource从文件系统目录中装载资源,可采用绝对或相对路径
http:// http://www.p7.com/resource/bean.xml 使用URLResource从Web服务器中装载资源
ftp:// ftp://www.p7.com/resource/bean.xml 使用URLResource从FTP服务器中装载资源
没有前缀 conf/bean.xml 根据ApplicationContext的具体实现采用对应类型的Resource

表格转自:https://blog.csdn.net/qq_30038111/article/details/82116559

Java资源访问

File

绝对路径
System.out.println(new File("/").getAbsolutePath());

输出电脑的根路径/,如果是windows,输出C:/

相对路径
System.out.println(new File(".").getAbsolutePath());

如果是javase,则输出运行main的路径。例如在D:/盘启动虚拟机,则输出的相对路径为D:/,如果是javaweb,比如说tomcat,则输出bin所在路径。

classpath

classpath包括自己写的java文件的字节码,还包括jar包的文件

Class
// 输出当前文件所在包的路径
System.out.println(Test.class.getResource("").getPath());
        
// 输出classpath的根路径
System.out.println(Test.class.getResource("/").getPath());
ClassLoader
// 输出classpath的根路径
System.out.println(Test.class.getClassLoader().getResource(""));
// 输出null,不存在此写法 System.out.println(Test.class.getClassLoader().getResource("/"));

UrlResource

url

如果是网址,则可以通过new UrlResource("https://www.baidu.com").getInputStream();获取字节流

本地文件

如果是本地文件,增加file:前缀可以获取file文件

// 获取项目根路径
System.out.println(new UrlResource("file:").getFile().getAbsolutePath());
// 获取本地根路径
System.out.println(new UrlResource("file:/").getFile().getAbsolutePath());
上一篇 下一篇

猜你喜欢

热点阅读