Spring boot操作文件 详解Spring boot操作文件的多种方式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring boot操作文件 详解Spring boot操作文件的多种方式

swimcode   2021-11-01 我要评论
想了解详解Spring boot操作文件的多种方式的相关内容吗,swimcode在本文为您仔细讲解Spring boot操作文件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring,,boot操作文件,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());

img

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());

img

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"));

img

二、操作文件的三种方式

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);

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们