.java和.class的区别与获取class文件的资源路径

注:.class文件,是.java源文件编译后的文件
1、一般src文件夹下的是.java源文件
2、我这里是out文件夹下的是.class文件
在这里插入图片描述

package package01;

public class Test01 {
    public Test01() {
    }

    public static void main(String[] args) {
        Test01 test01 = new Test01();
        test01.a();
    }

    public void a() {
        System.out.println("this.getClass().getResource(\"/\").getPath();" + this.getClass().getResource("/").getPath());
        System.out.println("this.getClass().getResource().getPath();" + this.getClass().getResource("").getPath());
    }
}

控制台输出:

/D:/Idea_workspace/Java_Test/out/production/Java_Test/
/D:/Idea_workspace/Java_Test/out/production/Java_Test/package01/

总结:

this.getClass().getResource("/").getPath() 获取的是到Java_Test文件夹的路径
this.getClass().getResource("").getPath() 获取的是准确到该.class文件所在的文件夹路径
所以后者比前者能获取到更精确的路径

发布了86 篇原创文章 · 获赞 1 · 访问量 4339

猜你喜欢

转载自blog.csdn.net/qq_42039738/article/details/105164158
今日推荐