java获取文件的路径怎么写

java获取文件的路径怎么写,第1张

java获取文件的路径怎么写

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/687097.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-21
下一篇 2022-04-21

发表评论

登录后才能评论

评论列表(0条)

保存