java加载文件的方式

来源:互联网 发布:宏源证券交易软件 编辑:程序博客网 时间:2024/05/22 10:51

   在javaSE编程中,主要有两种方式加载文件:(一)使用类加载器进行加载,(二)不使用类加载器

   首先创建一个java工程,工程的目录结构如下图所示:

 

注意:在src目录下的configer.propery中存放的内容为:configerPath = classpath.property;在com.xilin.jiong文件下的 configer.propery的内容为:configerPath = com.xilin.jiong.property

1.不使用类加载器的方式加载文件

public class ResourcePath {public static void main(String[] args) {InputStream inputStream = null;try {//获取要读取文件的输入流inputStream = Class.forName(ResourcePath.class.getName()).getResourceAsStream("configer.property");//调用读取文件的方法readProperty(inputStream);} catch (ClassNotFoundException e) {e.printStackTrace();} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}}/** * 读取文件的方法 * @param inputStream 输入文件流 */public static void readProperty(InputStream inputStream) {Properties properties = new Properties();try {properties.load(inputStream);} catch (IOException e) {e.printStackTrace();}System.err.println(properties.get("configerPath"));}}
此时运行的结果为:com.xilin.jiong.property。实际上此时读取的是com.xilin.jiong文件下的 configer.propery的内容。

当我们把inputStream = Class.forName(ResourcePath.class.getName()).getResourceAsStream("configer.property")稍微修改一下,将"configer.property"改为"/configer.property",此时的运行结果为:classpath.property。当加上斜杠的时候,文件是从该工程的ClassPath路径查找文件的。当没有反斜杠的时候,是从该Class类的当前文件中查询文件的。这个一定得注意彼此的区别!

2.使用类加载器读取文件

将上面的代码稍微修改一下,如下所示:

public class ResourcePath {public static void main(String[] args) {InputStream inputStream = null;inputStream =ResourcePath.class.getClassLoader().getResourceAsStream("configer.property");    readProperty(inputStream);if (inputStream != null) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}/** * 读取文件的方法 * @param inputStream 输入文件流 */public static void readProperty(InputStream inputStream) {Properties properties = new Properties();try {properties.load(inputStream);} catch (IOException e) {e.printStackTrace();}System.err.println(properties.get("configerPath"));}}
此时运行的结果为:classpath.property,读取的为src下的configer.property文件。如果要读取com.xilin.jiong.configer.property文件,需要将inputStream =ResourcePath.class.getClassLoader().getResourceAsStream("configer.property")中标红的修改为:"com/xilin/jiong/configer.property"


只需掌握其中一种方式即可!仅供参考............


1 0
原创粉丝点击