您的位置 首页 java

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://www.zhihuclub.com/22372.shtml

关于作者: 智云科技

热门文章

网站地图