java猎取文件的途径怎样写
我们在上传文件和文件处置惩罚的时刻须要猎取资本文件的途径。但是在项目中猎取的文件途径,能够并非我们想要的文件途径,由于开辟项目中猎取的途径与打成jar包后的途径并不一致。(引荐教程:java教程)
1. 猎取资本途径
String filePath = this.getClass().getResource("").getPath(); System.out.println("filePath: " + filePath);
在项目开辟中展现的途径:
filePath: /home/idea/project/java_basic/selfimpr-fileupload/target/classes/com/selfimpr/fileupload/controller/
在项目打成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. 猎取项目文件编译途径
String filePath = this.getClass().getResource("/").getPath(); System.out.println("filePath: " + filePath);
在项目开辟中展现的途径:
filePath: file:/home/idea/project/java_basic/selfimpr-fileupload/target/classes/
在项目打成jar包中的途径:
filePath: file:/home/idea/project/java_basic/selfimpr-fileupload/target/selfimpr-fileupload-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/
3. 猎取项目根途径(一)
File files = new File(""); String filePath = files.getCanonicalPath(); System.out.println("filePath: " + filePath);
在项目开辟中展现的途径:
filePath: /home/idea/project/java_basic
在项目打成jar包中的途径:
filePath: /home/idea/project/java_basic/selfimpr-fileupload/target
4. 猎取项目根途径(二)
String filePath = System.getProperty("user.dir"); System.out.println("filePath: " + filePath);
在项目开辟中展现的途径:
filePath: /home/idea/project/java_basic
在项目打成jar包中的途径:
filePath: /home/idea/project/java_basic/selfimpr-fileupload/target
5.开辟环境和jar环境都能运用
/* 此要领,传入参数为String,不能带/ */ resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("/templates" + url); /* 此要领,传入参数为String,不能带/ */ resourceAsStream = this.getClass().getResourceAsStream("/templates" + url);
此要领猎取的项目途径,不管是编译时期照样打成jar包的环境,都能猎取到resources途径下的文件。
以上就是java猎取文件的途径怎样写的细致内容,更多请关注ki4网别的相干文章!