java获取当前路径(包含tomcat)

1、利用System.getProperty()的函数 获取当前路径:

System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径


2、使用File提供的函数获取当前路径:

File directory = new File("");//设定为当前文件

try{

    System.out.println(directory.getCanonicalPath());//获取标准路径

    System.out.println(directory.getAbsolutePath());//获取绝对路径

}catch(Exception e){}


File.getCanonicalPath()和File.getAbsolutePath()大约只是对于new File(".")和new File("..")两种路径有所区别。


#对于getCanonicalPath()函数,"."就表示当前的文件夹,而“..”则表示当前文件夹的上一级文件夹

#多语言getAbsolutePath()函数,则不管“.”、"..",返回的是当前的路径加上你在new File()时设定的路径

#对于getPath()函数,得到的只是你在new File()时设定的路径


比如当前的路径为C:\test:

File directory = new File("abc");

directory.getCanonicalPath();//得到的是C:\test\abc

directory.getAbsolutePath();//得到的是C;\test\abc

directory.getPath();                //得到的是abc


File directory = new File(".");

directory.getCanonicalPath();//得到的是C:\test

directory.getAbsolutePath();//得到的是C:\test\.

directory.getPath();              //得到的是.


File directory = new File("..");

directory.getCanonicalPath();//得到的是C:

directory.getAbsolutePath();//得到的是C:\test\..

directory.getPath();              //得到的是..


另外还有一个方法可以用来获取类的绝对路径(当前的ClassPath)

getClass().getRecourec("/").toString();

例如:

        Demo demo = new Demo();

    String path = demo.getClass().getResource("/").toString();

        //获取到的是:file:/D:/workspace/web2/WebContent/WEB-INF/classes/



你可能感兴趣的:(java获取当前路径(包含tomcat))