25. // 开始读取文件内容
26. InputStream is = this.getClass().getResourceAsStream("/conf/test.properties");
27. Properties props = new Properties();
28. props.load(is);
29. Assert.assertTrue(props.containsKey("test.key"));
30. Assert.assertEquals("thisIsValue", props.getProperty("test.key"));
31. }
________________________________________
读取Jar内某路径下的所有文件
1. /**
2. * 从ClassPath中的Jar包读取某文件夹下的所有文件
3. *
4. * @author lihzh
5. * @throws IOException
6. * @data 2012-4-13 下午10:22:24
7. */
8. @Test
9. public void testGetFilesFromJarInClassPathWithDirPath() throws IOException {
10. String dirPath = "conf/";
11. URL url = this.getClass().getClassLoader().getResource(dirPath);
12. Assert.assertNotNull(url);
13. String urlStr = url.toString();
14. // 找到!/ 截断之前的字符串
15. String jarPath = urlStr.substring(0, urlStr.indexOf("!/") + 2);
17. JarURLConnection jarCon = (JarURLConnection) jarURL.openConnection();
18. JarFile jarFile = jarCon.getJarFile();
19. Enumeration
20. Assert.assertTrue(jarEntrys.hasMoreElements());
21. Properties props = new Properties();
22. while (jarEntrys.hasMoreElements()) {
23. JarEntry entry = jarEntrys.nextElement();
24. // 简单的判断路径,如果想做到想Spring,Ant-Style格式的路径匹配需要用到正则。
25. String name = entry.getName();
26. if (name.startsWith(dirPath) && !entry.isDirectory()) {
27. // 开始读取文件内容
28. InputStream is = this.getClass().getClassLoader().getResourceAsStream(name);
29. Assert.assertNotNull(is);
30. props.load(is);
31. }
32. }
33. Assert.assertTrue(props.containsKey("test.key"));
34. Assert.assertEquals("thisIsValue", props.getProperty("test.key"));
35. Assert.assertTrue(props.containsKey("test.key.two"));
36. Assert.assertEquals("thisIsAnotherValue", props.getProperty("test.key.two"));
37. }
________________________________________
对于不在ClassPath下的Jar包的读取,当作一个本地文件用JarFile读取即可。路径可使用绝对路径。或者用上面的url.getConnection也可以处理。这里不再实现。
PS:附件是测试用的jar包。
摘自 苦逼coder