我們在上傳文件和文件處理的時(shí)候需要獲取資源文件的路徑。但是在項(xiàng)目中獲取的文件路徑,可能并不是我們想要的文件路徑,因?yàn)殚_發(fā)項(xiàng)目中獲取的路徑與打成jar包后的路徑并不一致。
以一個(gè)SpingCloud項(xiàng)目為例,且有多個(gè)模塊
1. 獲取資源路徑
String filePath = this.getClass().getResource("").getPath();
System.out.println("filePath: " + filePath);
在項(xiàng)目開發(fā)中展示的路徑:filePath: /home/idea/project/java_basic/selfimpr-fileupload/target/classes/com/selfimpr/fileupload/controller/
在項(xiàng)目打成jar包中的路徑: filePath: file:/home/idea/project/java_basic/selfimpr-fileupload/target/selfimpr-fileupload-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/com/selfimpr/fileupload/controller/
2. 獲取項(xiàng)目文件編譯路徑
String filePath = this.getClass().getResource("/").getPath();
System.out.println("filePath: " + filePath);
在項(xiàng)目開發(fā)中展示的路徑: filePath: file:/home/idea/project/java_basic/selfimpr-fileupload/target/classes/
在項(xiàng)目打成jar包中的路徑: filePath: file:/home/idea/project/java_basic/selfimpr-fileupload/target/selfimpr-fileupload-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/
3. 獲取項(xiàng)目根路徑(一)
File files = new File("");
String filePath = files.getCanonicalPath();
System.out.println("filePath: " + filePath);
在項(xiàng)目開發(fā)中展示的路徑: filePath: /home/idea/project/java_basic
在項(xiàng)目打成jar包中的路徑: filePath: /home/idea/project/java_basic/selfimpr-fileupload/target
4. 獲取項(xiàng)目根路徑(二)
String filePath = System.getProperty("user.dir");
System.out.println("filePath: " + filePath);
在項(xiàng)目開發(fā)中展示的路徑: filePath: /home/idea/project/java_basic
在項(xiàng)目打成jar包中的路徑: filePath: /home/idea/project/java_basic/selfimpr-fileupload/target
5.開發(fā)環(huán)境和jar環(huán)境都能使用
/* 此方法,傳入?yún)?shù)為String,不能帶/ */
resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("/templates" + url);
/* 此方法,傳入?yún)?shù)為String,不能帶/ */
resourceAsStream = this.getClass().getResourceAsStream("/templates" + url);
此方法獲取的項(xiàng)目路徑,不管是編譯期間還是打成jar包的環(huán)境,都能獲取到resources路徑下的文件。