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

网友投稿 936 2022-11-26

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

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

目录一、获取文件路径1、class.getResource(path)2、ClassLoader.getResource(path)3、项目路径二、操作文件的三种方式1、ClassPath2、FileSystem3、UrlResource

一、获取文件路径

获取文件路径

1、class.getResource(path)

其中的参数path有两种形式,一种是以“/”开头的,另一种是不以"/"开头;

「以'/'开头的表示」:从项目的根路径下去获取文件即classPath目录下。

不以"/"开头:以该类对象所在位置**为根路径来进行查找的。

// 1.获取当前文件所在的路径

System.out.println(this.getClass().getResource("").getPath());

// 2.获取再 target 下 classpath 路径

System.out.println(this.getClass().getResource("/").getPath());

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(ryQECG"").getPath());

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

二、操作文件的三种方式

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("shttp://tatic/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);

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:OpenCV计算机视觉编程篇三《处理图像的颜色》
下一篇:Github全面详解-01Github介绍
相关文章

 发表评论

暂时没有评论,来抢沙发吧~