相对路径绝对路径分析

来源:互联网 发布:iphone同步软件 编辑:程序博客网 时间:2024/05/17 07:10
spring
1.ClassPathXmlApplicationContext
使用绝对路径需要添加file前缀
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{
    "file:D:/MyEclipse/studyspaces/webpro/WebRoot/WEB-INF/conf/applicationContext.xml"});
使用相对路径只能读放在WEB-INF/classes目录下的配置文件,也就是类根目录
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:appcontext.xml");
ApplicationContext factory = new ClassPathXmlApplicationContext("appcontext.xml");

2.FileSystemXmlApplicationContext
使用绝对路径,可以添加file前缀,也可以不添加
ctx = new FileSystemXmlApplicationContext("file:D:/MyEclipse/studyspaces/webpro/WebRoot/WEB-INF/conf/applicationContext.xml");
ctx = new FileSystemXmlApplicationContext("D:/MyEclipse/studyspaces/webpro/WebRoot/WEB-INF/conf/applicationContext.xml");
相对路径,用文件系统的路径,默认指项目的根路径
   ctx = new FileSystemXmlApplicationContext(new String[]{"WebRoot/WEB-INF/conf/applicationContext.xml"});
   ctx = new FileSystemXmlApplicationContext(new String[]{"src/appcontext.xml"});

使用了classpath:前缀,读取classpath下的相对路径
   ctx = new FileSystemXmlApplicationContext("classpath:appcontext.xml");
   
log4j配置文件存放路径

1.默认位置
src目录下,也就是类根目录。该目录下log4j能自动读取

2.自定义配置
默认读取的是项目根目录的路径:PropertyConfigurator.configure("src/log4j.properties");
指定classpath相对路径
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/conf/test.txt"));//projectName/src/conf/test.txt
PropertyConfigurator.configure(props)

Java相对路径绝对路径分析
// 项目根路径
File file = new File("test/com/pj/test.txt");
System.out.println(file.isFile());

// 项目根路径--projectName/note.txt---D:\MyEclipse\studyspaces\webpro
System.out.println(System.getProperty("user.dir"));

// classpath相对路径 --projectName/src/
System.out.println(getClass().getResourceAsStream("/com/pj/test.txt"));
// 类文件路径 --projectName/src/com/pj/test.txt
System.out.println(getClass().getResourceAsStream("test.txt"));

// classpath相对路径--file:/D:/MyEclipse/studyspaces/webpro/WebRoot/WEB-INF/classes/
System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));

// classpath相对路径--file:/D:/MyEclipse/studyspaces/webpro/WebRoot/WEB-INF/classes/
System.out.println(PathTest.class.getClassLoader().getResource(""));

// classpath相对路径--file:/D:/MyEclipse/studyspaces/webpro/WebRoot/WEB-INF/classes/
System.out.println(ClassLoader.getSystemResource(""));

// 类文件路径--file:/D:/MyEclipse/studyspaces/webpro/WebRoot/WEB-INF/classes/com/pj/
System.out.println(PathTest.class.getResource(""));
// classpath相对路径--file:/D:/MyEclipse/studyspaces/webpro/WebRoot/WEB-INF/classes/
System.out.println(PathTest.class.getResource("/"));
0 0