this.getClass().getResource()

this.getClass().getResource()

package test;

import org.junit.Test;

import java.io.File;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 * User: ASUS
 * Date: 14-7-3
 * Time: 下午1:46
 * To change this template use File | Settings | File Templates.
 */
public class TestPath {

    /**
     * 项目名称叫做HelloWorld
     */
    @Test
    public void test() {
        URL url = this.getClass().getResource("/"); //得到的是当前的classpath的绝对路径
        if (url != null) {
            System.out.println(url.toString()); //打印file:/D:/JetBrains/HelloWorld/out/production/HelloWorld/
        } else {
            System.out.println("resource \"/\" were not found!!!");
        }

        URL url1 = this.getClass().getResource("");
        System.out.println(url1.toString()); //打印file:/D:/JetBrains/HelloWorld/out/production/HelloWorld/test/

        URL url2 = this.getClass().getResource("/name");
        if (url2 == null) {
            System.out.println("resource \"/name\" were not found!!!"); //resource "/name" were not found!!!
        } else {
            System.out.println(url2.toString());
        }
        URL url3 = this.getClass().getResource("/test");
        if (url3 == null) {
            System.out.println("resource \"/test\" were not found!!!");
        } else {
            System.out.println(url3.toString());   //打印file:/D:/JetBrains/HelloWorld/out/production/HelloWorld/test
            String file = url3.getFile();
            System.out.println(file);  //打印/D:/JetBrains/HelloWorld/out/production/HelloWorld/test
            File file1 = new File(file);
            if (file1.exists()) {
                System.err.println("sdsdsd");
            }
        }
    }
}

classpath的绝对路径

this.getClass().getResource("/"); //得到的是当前的classpath的绝对路径

下面是得到当前类所在路径的绝对路径

URL url1 = this.getClass().getResource("");
System.out.println(url1.toString()); //打印file:/D:/JetBrains/HelloWorld/out/production/HelloWorld/test/

==================END==================


你可能感兴趣的:(this.getClass().getResource())