2.2 文件的载入方式(例如配置文件等)


假设在com.alexia.A类里想读取文件夹 /com/alexia/config 里的文件sys.properties,读取文件可以通过绝对路径或相对路径,绝对路径很简单,在Windows下以盘号开始,在Unix下以"/"开始。对于相对路径,其相对值是相对于ClassLoader的,因为ClassLoader是一棵树,所以这个相对路径和ClassLoader树上的任何一个ClassLoader相对比较后可以找到文件,那么文件就可以找到。文件有以下三种加载方式:

1. 直接用IO流读取 

File f = new File("C:/test/com/aleixa/config/sys.properties"); // 使用绝对路径

//File f = new File("com/alexia/config/sys.properties"); // 使用相对路径

InputStream is = new FileInputStream(f);


2. 使用ClassLoader  

InputStream is = null;

is = this.getClass().getClassLoader().getResourceAsStream(

"com/alexia/config/sys.properties"); //方法1

//is = Thread.currentThread().getContextClassLoader().getResourceAsStream(

"com/alexia/config/sys.properties"); //方法2

//is = ClassLoader.getSystemResourceAsStream("com/alexia/config/sys.properties"); //方法3


3. 使用ResourceBundle 

ResourceBundle bundle = ResourceBundle.getBoundle("com.alexia.config.sys");


原载于:联动北方

全文:http://bbs.landingbj.com/t-0-241353-1.html