温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring boot如何操作文件

发布时间:2021-11-01 17:43:48 来源:亿速云 阅读:196 作者:小新 栏目:开发技术

小编给大家分享一下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());

Spring boot如何操作文件

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

Spring boot如何操作文件

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

Spring boot如何操作文件

二、操作文件的三种方式

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

看完了这篇文章,相信你对“Spring boot如何操作文件”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI