最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Spring boot操作文件的多种方式代码示例
时间:2021-11-01 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下Spring boot操作文件的多种方式代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
一、获取文件路径
获取文件路径
1、class.getResource(path)
其中的参数path有两种形式,一种是以“/”开头的,另一种是不以"/"开头;
「以'/'开头的表示」:从项目的根路径下去获取文件即classPath目录下。
不以"/"开头:以该类对象所在位置**为根路径来进行查找的。
// 1.获取当前文件所在的路径 System.out.println(this.getClass().getResource("").getPath()); // 2.获取再 target 下 classpath 路径 System.out.println(this.getClass().getResource("/").getPath());
< alt="" src="http://.111com.net/attachment/art/204435/63546ff568.png" data-ke-src="http://.111com.net/attachment/art/204435/63546ff568.png" style="height:auto;" />
class.getResource()和class.getResourceAsStream()方式的使用在路径上是一致的。
2、ClassLoader.getResource(path)
// 3.也是获取 classpath 的绝对路径 System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath()); // 4.也是获取 classpath 的绝对路径 System.out.println(this.getClass().getClassLoader().getResource("").getPath()); // 5.也是获取 classpath 的绝对路径 System.out.println(ClassLoader.getSystemResource("").getPath());
< alt="" src="https://.jbzj.com/file_images/article/202111/2021110116322586.png" data-ke-src="https://.jbzj.com/file_images/article/202111/2021110116322586.png" />
3、项目路径
//6.获取当前项目路径(此方法与 7 效果相同,但是可以将路径转为标准形式,会处理"."和"..") System.out.println(new File("").getCanonicalPath()); // 7.获取项目绝对路径(不会处理"."和"..") System.out.println(new File("").getAbsolutePath()); //8.user.dir System.out.println(System.getProperty("user.dir"));
< src="https://.jbzj.com/erweima/javajsmb.png" data-ke-src="https://.jbzj.com/erweima/javajsmb.png" alt="" />
< alt="" src="https://.jbzj.com/file_images/article/202111/2021110116322587.png" data-ke-src="https://.jbzj.com/file_images/article/202111/2021110116322587.png" />
二、操作文件的三种方式
1、ClassPath
读取resources下配置文件【文件只能为Properties、xml、JSON】
//读取 ClassPath 下的文件信息 //1、类加载器 InputStream resourceAsStream = DaoFactory.class.getClassLoader().getResourceAsStream("data.properties"); //2、当前线程加载器 lassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream is = classLoader.getResourceAsStream(path);
2、FileSystem
指定文件路径的方式读取文件信息,读取resources下static文件夹中的文件
String path = Thread.currentThread().getContextClassLoader().getResource("static/internal.csv").getPath(); File file = new File(path);
3、UrlResource
通过 HTTP 的方式读取云服务的文件,我们也可以把配置文件放到 GitHub 或者 Gitee 上。
URLConnection con = this.url.openConnection(); InputStream inputStream = con.getInputStream(); String content = IoUtil.readUtf8(inputStream); System.out.println(content);
-
上一个: Java数组的去重代码示例
相关文章
- SpringBoot测试配置属性与web启动环境解析 10-24
- vue中将el-switch值true、false改为number类型的1和0解析 10-24
- Vue中的路由配置项meta使用解读 10-24
- SpringBoot自定义bean绑定解析 10-24
- SpringBoot常用计量与bean属性校验和进制数据转换规则解析 10-24
- 工厂方法在Spring框架中的运用介绍 10-24