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 CodeClassLoader loader = TestCase2.class.getClassLoader();
/**
* Code Part 1
*/
URL url = loader.getResource(TestCase1.class.getName().replaceAll("\\.","/")+".class");
String path = url.getPath();
// here the output will be "/D:/TestProject/bin/testcase/TestCase1.class"
/**
* Code Part 2
*/
URL url = loader.getResource(TestCase2.class.getName().replaceAll("\\.","/")+".class");
String path = url.getPath();
// here the output will be "/D:/TestProject/bin/testcase/TestCase2.class"
/**
* Code Part 3
*/
String rawPath = "subfolder/"+TestCase3.class.getName();
URL url = loader.getResource(rawPath.replaceAll("\\.","/")+".class");
String path = url.getPath();
// here the output will be "/D:/TestProject/bin/testcase/subfolder/TestCase3.class"
没有评论:
发表评论