SpringBoot中jar啟動下如何讀取文件路徑
SpringBoot jar啟動下讀取文件路徑
由于我們經(jīng)常使用jar 包作為我們的項目啟動方式 以及我們經(jīng)常會設(shè)涉及到生成文件這時候就需要一個文件路勁存放臨時文件 因為我們正在存放可以在第三方服務(wù)器或者自己文件服務(wù)器。
下面就介紹一種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";
}
截圖如下




最后處理完業(yè)務(wù)邏輯 上傳到自己服務(wù)器 后刪除臨時文件
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
返回完整路徑
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java中Cookie和Session詳解及區(qū)別總結(jié)
這篇文章主要介紹了Java中Cookie和Session詳解,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下2022-06-06
springboot跨域訪問cros與@CrossOrigin注解詳析
這篇文章主要給大家介紹了關(guān)于springboot跨域訪問cros與@CrossOrigin注解的相關(guān)資料,跨域是指不同域名之間相互訪問,它是瀏覽器的同源策略造成的,是瀏覽器對JavaScript施加的安全限制,需要的朋友可以參考下2023-12-12
springboot實現(xiàn)注冊加密與登錄解密功能(demo)
這篇文章主要介紹了springboot實現(xiàn)注冊的加密與登錄的解密功能,本文通過demo實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02

