首先谈谈如何获取project中指定路径下的文件
(1)ClassLoader提供了两个方法用于从装载的类路径中取得资源:
public URL getResource(String name);
public InputStream getResourceAsStream(String name);
这里name是资源的类路径,它是相对与“/”根路径下的位置。getResource得到的是一个URL对象来定位资源,而getResourceAsStream取得该资源输入流的引用保证程序可以从正确的位置抽取数据。
但 是真正使用的不是ClassLoader的这两个方法,而是Class的 getResource和getResourceAsStream方法,因为 Class对象可以从你的类得到(如YourClass.class或 YourClass.getClass()),而ClassLoader则需要再 调用一次YourClass.getClassLoader()方法,不过根据JDK文档的说法,Class对象的这两个方法其实是“委托”(delegate)给装载它的ClassLoader来做的,所以只需要使用 Class对象的这两个方法就可以了。
因此,直接调用 this.getClass().getResourceAsStream(String name);获取流,静态化方法中则使用ClassLoader.getSystemResourceAsStream(String name); 。
(2)获取当前当前ClassPath的绝对URI路径的几种写法:
this.getClass().getResource("")
this.getClass().getResource("/")
this.getClass().getClassLoader().getResource("")
ClassLoader.getSystemResource("")
Thread.currentThread().getContextClassLoader().getResource("")
其次再是文件的读写:
public static String getStringProperty(String keyName,
String propertyFileName) throws IOException {
InputStream inputStream = ClassLoader
.getSystemResourceAsStream(propertyFileName);
Properties props = new Properties();
props.load(inputStream);
return props.getProperty(keyName);
}
public static void updateStringProperty(String keyName, String value,
String propertyFileName) throws IOException, URISyntaxException {
File file = new File(ClassLoader.getSystemResource(propertyFileName).toURI());
InputStream inputStream = new FileInputStream(file);
Properties props = new Properties();
props.load(inputStream);
inputStream.close();
OutputStream outputStream = new FileOutputStream(file);
props.setProperty(keyName, value);
props.store(outputStream, "update properties:" + keyName + " to "
+ value);
outputStream.close();
}