这样的代码在工程中访问没有问题,但是该工程打成jar包给其他project使用时,出现读文件的错误。
因为".../MyprojectJar.jar!/resource/...."并不是文件资源定位符的格式(jar中资源有其专门的URL形式:jar:!/{entry})。所以,如果jar包中的类源代码用File f=new File(相对路径);的形式,是不可能定位到文件资源的。这也是为什么源代码1打包成jar文件后,调用jar包时会报出FileNotFoundException的症结所在了。
稍作修改
InputStream is=this.getClass().getResourceAsStream(path);
BufferedReader br=new BufferedReader(new InputStreamReader(is));
这样就可以了
public Vector readConfigInfo(String path){
String rpath=this.getClass().getResource("").getPath().substring(1)+path;
Vector dsConfig=null;
FileInputStream fi = null;
InputStream is=this.getClass().getResourceAsStream(path);
BufferedReader br=new BufferedReader(new InputStreamReader(is));
try{
fi=new FileInputStream(rpath);//读取路径文件 dsConfig=new Vector(); SAXBuilder sb=new SAXBuilder(); Document doc=sb.build(br); Element root=doc.getRootElement(); List pools=root.getChildren(); Element pool=null; Iterator allPool=pools.iterator(); while(allPool.hasNext()) { pool=(Element)allPool.next(); DSConfigBean dscBean=new DSConfigBean(); dscBean.setType(pool.getChild("type").getText()); dscBean.setName(pool.getChild("name").getText()); System.out.println(dscBean.getName()); dscBean.setDriver(pool.getChild("driver").getText()); dscBean.setUrl(pool.getChild("url").getText()); dscBean.setUsername(pool.getChild("username").getText()); dscBean.setPassword(pool.getChild("password").getText()); dscBean.setMaxconn(Integer.parseInt(pool.getChild("maxconn").getText())); dsConfig.add(dscBean); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return dsConfig; }