jar启动下读取文件路径

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

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

jar启动下读取文件路径

蜗牛乌龟一起走   2022-06-20 我要评论

SpringBoot jar启动下读取文件路径

由于我们经常使用jar 包作为我们的项目启动方式 以及我们经常会设涉及到生成文件这时候就需要一个文件路劲存放临时文件 因为我们正在存放可以在第三方服务器或者自己文件服务器。

下面就介绍一种jar 下生成文件存放示例。

代码如下

@GetMapping("/index")
	public String getFile() throws IOException {
		try {
			File path = new File(ResourceUtils.getURL("classpath:").getPath());
			if (!path.exists()) {
				path = new File("");
				System.err.println("path" + path.getAbsolutePath());
			}
			File upload = new File(path.getAbsolutePath(), "static/temp/");
			if (!upload.exists()) {
				boolean mkdirs = upload.mkdirs();
				String text = "drj测试";
				FileOutputStream fos = new FileOutputStream(upload.getAbsolutePath() +File.separator+ "drj.txt");
				fos.write(text.getBytes());
				fos.close();
				System.err.println("不存在" + mkdirs);
			} else {
				System.err.println(upload.getAbsolutePath());
				System.err.println("存在");
			}
			return "success";
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "error";
	}

截图如下

最后处理完业务逻辑 上传到自己服务器 后删除临时文件

SpringBoot获取路径的方式

前置条件

http://127.0.0.1:9001/aiforce/authentication/sso

1)request.getContextPath()

/aiforce

2)request.getServletPath()

/authentication/sso

只返回传递到servlet的路径

3)request.getPathInfo()

/authentication/sso

只返回传递到servlet的路径

4)request.getRequestURI

/aiforce/authentication/sso

5)request.getRequestURL

http://localhost:9001/aiforce/authentication/sso

返回完整路径

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

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

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