Support Wikipedia Follow My Heart: How to get the file path of current/target class in JAVA?

2011年10月15日星期六

How to get the file path of current/target class in JAVA?

Sometimes, we need to get the absolute path of some class, i.e. "D:\TestProject\bin\org\apache\....."

I recommend to use the ClassLoader.getResource() method. Because this method can also fetch back the file path even within the jar package.
Now let me show you a simple demo.
Assuming that we have the following folder in Disk D:
D:\ TestProject
        |----->   src
        |----->   bin
                      |  ------> testcase
                                         |--------> TestCase1.class
                                         |--------> TestCase2.class
                                         |--------> subfolder
                                                             |---------> TestCase3.class
so ,  actually the paths of these testcases are as follows:
Class Name Absolute Path
TestCase1.class D:\TestProject\bin\testcase\TestCase1.class
TestCase2.class D:\TestProject\bin\testcase\TestCase2.class
TestCase3.class D:\TestProject\bin\testcase\subfolder\TestCase3.class
Now, assuming that we are inside TestCase2,  so by following codes, we can get all these paths.
Reference Code

没有评论:

发表评论