参考: |
代码中使用到文件的位置:
|
|
代码示例:
package path;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import org.junit.Test;
import MybatisTest.utils.MbDbUtils;
public class PathTest {
/**
*
* @throws FileNotFoundException
* @throws IOException
* java中各种获取路径的方式:
*
*/
@Test
public void testPath() throws FileNotFoundException, IOException {
/*
* 1,获取指定的资源路径
* Consloe1:/E:/MyEclipse2014WorkSpace/AJavaTestPro/WebRoot/WEB-INF/classes/mysqldb.properties
* Consloe2:/E:/MyEclipse2014WorkSpace/AJavaTestPro/WebRoot/WEB-INF/classes/P1/test.txt
*/
URL url = ClassLoader.getSystemResource("mysqldb.properties");
System.out.println("console1:"+url.getPath());
//
URL systemResource = ClassLoader.getSystemResource("P1/test.txt");
System.out.println("console2:"+systemResource.getPath());
/*
* 2,获取指定类所在路径
* Console:/E:/MyEclipse2014WorkSpace/AJavaTestPro/WebRoot/WEB-INF/classes/MybatisTest/utils/
*/
URL resource = MbDbUtils.class.getResource("");
System.out.println(resource.getPath());
/*
*,3,获取指定类所在根路径
* Console:/E:/MyEclipse2014WorkSpace/AJavaTestPro/WebRoot/WEB-INF/classes/
*/
URL resource2 = MbDbUtils.class.getResource("/");
System.out.println(resource2.getPath());
/*
*,4,获取项目根目录的绝对路径
* console:E:\MyEclipse2014WorkSpace\AJavaTestPro
*/
String property = System.getProperty("user.dir");
System.out.println(property);
/*
*,5,获取类路径和包路径
* console:
jcp:E:\MyEclipse2014WorkSpace\AJavaTestPro\WebRoot\WEB-INF\classes
jcp:E:\MyEclipse2014WorkSpace\AJavaTestPro\WebRoot\WEB-INF\lib\ant-1.9.6.jar
jcp:E:\MyEclipse2014WorkSpace\AJavaTestPro\WebRoot\WEB-INF\lib\ant-launcher-1.9.6.jar
jcp:E:\MyEclipse2014WorkSpace\AJavaTestPro\WebRoot\WEB-INF\lib\antlr-2.7.7.jar
jcp:E:\MyEclipse2014WorkSpace\AJavaTestPro\WebRoot\WEB-INF\lib\aopalliance.jar
jcp:E:\MyEclipse2014WorkSpace\AJavaTestPro\WebRoot\WEB-INF\lib\asm-5.2.jar
jcp:E:\MyEclipse2014WorkSpace\AJavaTestPro\WebRoot\WEB-INF\lib\aspectjrt.jar
jcp:E:\MyEclipse2014WorkSpace\AJavaTestPro\WebRoot\WEB-INF\lib\aspectjweaver.jar
jcp:E:\MyEclipse2014WorkSpace\AJavaTestPro\WebRoot\WEB-INF\lib\c3p0-0.9.2.1.jar
jcp:E:\MyEclipse2014WorkSpace\AJavaTestPro\WebRoot\WEB-INF\lib\cglib-3.2.5.jar
jcp:E:\MyEclipse2014WorkSpace\AJavaTestPro\WebRoot\WEB-INF\lib\commons-fileupload-1.3.2.jar
...
*/
String property2 = System.getProperty("java.class.path");
String[] split = property2.split(";");
for (String string : split) {
System.out.println("jcp:"+string);
}
}
}