您的位置:首页 > 其它

关于ClassLoader.getResouce打包配置文件放外面的方法

2014-07-09 14:29 316 查看
实际上都是抄的,但是看了很多归纳了一下

这篇文章主要解决动态路径访问的问题,打jar包找配置文件问题,相对src目录读取其他位置文件问题

如果你仔细看,这几个问题都能解决

Class.getResource与Class.getClassLoader.getResource

这两个getResource()是使用当前ClassLoader加载资源(即资源在 Class path中),这样资源和class直接打在jar包中,避免文件路径问题.

两者不同是Class的getResource()方法是从当前.class文件路径查找资源,ClassLoader则是从jar包根目录查找.

注意:针对WEB的javaEE项目和javaSE项目,路径也是有所不同的。

下面是代码的例子,注意"/"的使用



package com.chinaso.phl;

/**
* @author piaohailin
* @date   2013-12-16
*/
public class Main {

public static void main(String[] args) {
System.out.println(Main.class.getResource("a.txt"));
System.out.println(Main.class.getResource("/a.txt"));
System.out.println(Main.class.getResource("/"));
System.out.println(Main.class.getResource("b.txt"));
// need to add resource/b.txt to build path! it will be package in jar file
System.out.println(Main.class.getClassLoader().getResource("b.txt"));
System.out.println(Main.class.getClassLoader().getResource("/"));
System.out.println(Thread.currentThread().getContextClassLoader().getResource("b.txt"));
}
}
eclipse中的输出结果

file:/I:/project/eclipse3.6/java.getResource/bin/com/chinaso/phl/a.txt

null

file:/I:/project/eclipse3.6/java.getResource/bin/

null

file:/I:/project/eclipse3.6/java.getResource/bin/b.txt

null

file:/I:/project/eclipse3.6/java.getResource/bin/b.txt

打包以后输出的结果

C:\my>java -classpath my.jar;b.txt com.chinaso.phl.Main

jar:file:/C:/my/my.jar!/com/chinaso/phl/a.txt

null

null

null

jar:file:/C:/my/my.jar!/b.txt

null

jar:file:/C:/my/my.jar!/b.txt

先不说这运行结果是否跟上面相同。但是仔细看,打jar包和打包后的输出路径不一致,这就说明,打包的时候要注意这些东西。免得出错。

另外这样表示,可能仅仅表示出了路径。

再仔细看看有的只有路径,有的却在前面有个file:这个东西,这个很重要,它表示这是一个文件,而不是路径

所以容易犯这样的错误,就是直接指向文件,但是没加file而出错。

String pathString="file:"+System.getProperty("user.dir");

这句话指输出是file:D:\java\workspace\myapp\com.app.test 直接定位到你程序的目录,配置文件放在附近就能读到

这个就能表示你现在想指向的文件的路径设置,是相对于你现在class文件锁放的位置,可以把它打印出来看看。

打包时候,想把配置文件放到包外面,主要就要靠这几个操作。

另外,如果你要读properties文件的话,需要用到加载文件这个操作。

String in = pathString+propertiesfile;
props.load(new FileInputStream(new File(in)));
String value = props.getProperty(key);


这个inputstream和fileinputstream是有区别的,到时候要注意。

我的程序放上面 体会体会吧

public static void main(String args[]){
String pathString="file:"+System.getProperty("user.dir")+"\\applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(pathString);
App e = (App) ctx.getBean("entry");
e.excute();

}


spring的配置文件,不一定放到src里面,放到外面也是能读到的,刚好就是你现在程序的平行位置

假设你这是一个jar包,你想把spring配置文件,或者properties文件放到外面就可以直接这样调用,把配置文件放到jar包的平行位置,可以动态加载,以方便替换

另外,如果你对maven很熟的话,可以自定义一个目录专门用来放这些东西。每次都直接mvn install顺便把配置文件放到这里,不用手动添加。

对maven不是很熟也没关系,直接手动复制就行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐