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获取文件的路径怎么写的详细内容。