目录
  • SpringBoot jar启动下读取文件路径
    • 代码如下
    • 截图如下
  • SpringBoot获取路径的方式
    • 前置条件

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中jar启动下如何读取文件路径

SpringBoot中jar启动下如何读取文件路径

SpringBoot中jar启动下如何读取文件路径

SpringBoot中jar启动下如何读取文件路径

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

SpringBoot获取路径的方式

前置条件

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

SpringBoot中jar启动下如何读取文件路径

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

返回完整路径

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。