【spring】【spring boot】獲取系統根路徑,根目錄,用於存儲臨時生成的文件在服務器上


 

今日份代碼:

Spring

private static final String UPLOAD_TEMP_FILE_NAME = "測試商品數據.xlsx";   /** * 獲取臨時文件路徑 * @return
     */
    private String getFilePath(){ String path = 當前類.class.getResource("/").getPath()+UPLOAD_TEMP_FILE_NAME; return path; }

 

 

 Spring Boot:

 

    //第一種
        File path = new File(ResourceUtils.getURL("classpath:").getPath()); if(!path.exists()) path = new File(""); System.out.println(path.getAbsolutePath()); //第二種
        System.out.println(System.getProperty("user.dir")); //第三種
        String path1 = ClassUtils.getDefaultClassLoader().getResource("").getPath(); System.out.println(URLDecoder.decode(path1, "utf-8")); //第四種
        String path2 = ResourceUtils.getURL("classpath:").getPath(); System.out.println(path2); //第五種 spring boot打jar包,建議使用第五種
        ApplicationHome h = new ApplicationHome(getClass()); File jarF = h.getSource(); System.out.println(jarF.getParentFile().toString()); //第六種 spring boot打jar包或者不打包,都可以使用的,建議區分系統以完善路徑 本種也建議使用
         Properties properties = System.getProperties(); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>系統:" + properties.getProperty("os.name")); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>根路徑" + properties.getProperty("user.dir")); String path = properties.getProperty("user.dir"); if (properties.getProperty("os.name").toLowerCase().contains("win")) { path += "\\"; }else { path += "/"; }

 

 

 

 

使用第五種示例如下:

 

private static final String UPLOAD_TEMP_FILE_NAME = "測試商品數據.xlsx";   /** * 獲取臨時文件路徑 * @return
     */
    private String getFilePath(){ ApplicationHome h = new ApplicationHome(getClass()); File jarF = h.getSource(); String path = jarF.getParentFile().toString(); int i = path.lastIndexOf("/"); if (i > 0) { path = path.substring(0,i+1); } path += UPLOAD_TEMP_FILE_NAME; return path; }

 

 

使用第六種示例如下:

windows本機未打包運行結果: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>系統:Windows 10
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>根路徑E:\document\ideaProject\p-job Linux打jar包運行結果: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>系統:Linux >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>根路徑/data/web/domains/p-job.com/server8097
private static final String UPLOAD_TEMP_FILE_NAME = "測試商品數據.xlsx";   /** * 獲取臨時文件路徑 * @return
     */
    private String getFilePath(){ Properties properties = System.getProperties(); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>系統:" + properties.getProperty("os.name")); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>根路徑" + properties.getProperty("user.dir")); String path = properties.getProperty("user.dir"); if (properties.getProperty("os.name").toLowerCase().contains("win")) { path += "\\"; }else { path += "/"; } path += UPLOAD_TEMP_FILE_NAME; return path; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM