一。一些取path的方法
//eclipse Test项目下面的测试类
package path;
import java.io.File;
public class PathTest {
public static void main(String[] args) throws Exception {
//file:/E:/java/workspace/test/bin/
System.out.println(Thread.currentThread().getContextClassLoader()
.getResource(""));
System.out.println(PathTest.class.getClassLoader().getResource(""));
System.out.println(ClassLoader.getSystemResource(""));
System.out.println(PathTest.class.getResource("/"));
//file:/E:/java/workspace/test/bin/path/
System.out.println(PathTest.class.getResource(""));
//E:\java\workspace\test
System.out.println(new File("").getAbsolutePath());
System.out.println(System.getProperty("user.dir"));
}
}
二。getResourceAsStream() 本方法使用相对classpath的根路径。
引用来自:http://blog.youkuaiyun.com/yangm1203/archive/2007/07/11/1685839.aspx
Class.getResourceAsStream() & ClassLoader的getResourceAsStream()
注意两点:
1,用Class.getResourceAsStream() 时,路径应该是以"/"开头的,如:
mypackage.Hello.class.getResourceAsStream("/ config/config.ini");
2,如果直接用ClassLoader的getResourceAsStream() 不用以"/"开头.如,
mypackage.Hello.class.getResourceAsStream("config/config.ini ");
!!注意文件放置的位置,应该放在classpath下 .
在eclipse项目我们通常将java代码和config配置文件分目录放,如下图
那么config目录下的config.ini是不是"config/config.ini "呢? 答案是NO!
因为项目编译后,config.ini会放在classpath的根目录,而不是config目录。
本文深入探讨了Java中获取类路径、资源的方法,包括如何使用Thread.currentThread().getContextClassLoader()、PathTest.class.getClassLoader().getResource()、ClassLoader.getSystemResource()及PathTest.class.getResource()等方法,并详细解释了getResourceAsStream()方法的使用与注意事项。

被折叠的 条评论
为什么被折叠?



