获取classpath下路径的方法
方法1(返回绝对路径):
URL url = Thread.currentThread().getContextClassLoader().getResource(""font/simkai.ttf"");
String path = url.getPath();
方法2:
InputStream inputStream = JdbcUtil.class.getResourceAsStream("/jdbc.properties");
以上方法的意思是在classpath路径下查找jdbc.properties。如要打成一个jar包形式建议用这个方法获取资源文件, 如用方法1获取是会有问题的,因为方法1是获取的绝对路径,运行java -jar test.jar后获取的路径会是 d:/test.jar!/jdbc.properties这种样子,导致路径不正确,多了个叹号,在Eclipse下运行正常。
示例1:加载properties文件
Properties properties = new Properties();InputStream inputStream = JdbcUtil.class.getResourceAsStream("/jdbc.properties");try { properties.load(inputStream);} catch (FileNotFoundException e1) { log.error(e1.getMessage(), e1);} catch (IOException e1) { log.error(e1.getMessage(), e1);} finally { try { inputStream.close(); } catch (IOException e) { log.error(e); }}driver = properties.getProperty("jdbc.driver");url = properties.getProperty("jdbc.url");username = properties.getProperty("jdbc.username");password = properties.getProperty("jdbc.password"); InputStream in = GenerateBaseDataServiceImpl.class.getResourceAsStream("/tableInfo.xml"); try { SAXReader reader = new SAXReader(); Document doc = reader.read(in); Element root = doc.getRootElement(); Iterator<?> iterator = root.elementIterator("baseData"); Element subElement; String tableSchema; String tableName; String sqlStatement; TableInfo tableInfo = null; while (iterator.hasNext()) { subElement = (Element) iterator.next(); tableSchema = subElement.attribute("tableSchema").getText(); tableName = subElement.attribute("tableName").getText(); Attribute sqlStatementAttribute = subElement.attribute("sqlStatement"); tableInfo = new TableInfo(); if (sqlStatementAttribute != null) { sqlStatement = sqlStatementAttribute.getText(); tableInfo.setSqlStatement(sqlStatement); } tableInfo.setTableSchema(tableSchema); tableInfo.setTableName(tableName); tableInfoList.add(tableInfo); } } catch (DocumentException e) { log.error("读取基础数据的xml出错", e); } finally { try { in.close(); } catch (IOException e) { log.error(e.getMessage(), e); } }