且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java工程路径及相对路径(转载)

更新时间:2022-08-22 14:55:26

 3. 新建文件,默认位于工程目录
new File("xxx.txt").getAbsolutePath();
例如输出,D:\workspaces\workspace1\myProject
如果使用ClassName.class.getResource("name.config")的结果作为File对象的参数,则会报错:

java.io.FileNotFoundException: file:\D:\workspaces\workspace1\myProject\bin\com\hutu\log4j\name.config (文件名、目录名或卷标语法不正确。)
at java.io.FileInputStream.open(Native Method)

 
 4. 配置文件路径
ApplicationContext context = new ClassPathXmlApplicationContext("Config.xml");
.xml, .properties等,默认还是从“工程目录”去找的
1). 倒是也可以用绝对路径,真心不推荐啊,太不优雅了;
2). 或者,将log4j文件置于bin/目录下:
     a). 代码中,PropertyConfigurator.configure("bin/log4j.properties");
     b). 代码中,PropertyConfigurator.configure(ClassLoader.getSystemResource("log4j.properties"));
     c). 注意,必须位于bin直接目录下,不可位于bin更深层的目录当中。可是这究竟是为神马捏?
 5. 查询某类的.class文件所在目录
Main.class.getResource(“”);
例如输出,file:/D:/workspaces/workspace1/myProject/bin/com/hutu/log4j/
注意,查询包上级路径,只需将参数改作“/”
 6. 查询thread上下文所在目录
Thread.currentThread().getContextClassLoader().getResource("");
例如输出,D:\workspaces\workspace1\myProject\bin\
 7. 查询某类的classloader所在目录
Main.class.getClassLoader().getResource("");
例如输出,D:\workspaces\workspace1\myProject\bin\
 8. 查询classloader所在目录
ClassLoader.getSystemResource("");
例如输出,D:\workspaces\workspace1\myProject\bin\

 class.getResourceAsStream("path")、class.getClassLoader().getResourceAsStream("path")区别的分析
class.getResourceAsStream("path"):如果path仅为一个文件名,则只会在包路径下查找,当path以“/”开头时,则会从classpath的根路径开始查找(SRC根目录)
class.getClassLoader().getResourceAsStream("path"):无论要查找的资源前面是否有"/"都是从classpath的根路径下查找。