---
title: "【java】由读取properties文件联想到的......"
author: "cectsky"
date: "2011-04-21T16:02:33Z"
tags: []
categories: ["编程语言"]
slug: "java-properties"
draft: false
lastmod: "2011-04-21T16:02:33Z"
id: 1011369
url: "https://cectsky.iteye.com/blog/1011369"
---

下午闲来无事，看了一个教程，关于读取properties的方法，其实，这种代码网上一大片一大片的，都懒的看了。说说我联想到了什么吧。

 

 首先是getResourceAsStream()方法，就是从stream中获取resource而已，那么这个方法是谁提供的呢？

 

角色之一：ClassLoader

 

```
 public InputStream getResourceAsStream(String name) {
 URL url = getResource(name);
 try {
     return url != null ? url.openStream() : null;
 } catch (IOException e) {
     return null;
 }
    }
```

```
这里都是要找老子帮忙的，他爸是李刚吧，nonono，是Bootstrap刚。。。
```

```
public URL getResource(String name) { 
 URL url;
 if (parent != null) {
     url = parent.getResource(name);
 } else {
     url = getBootstrapResource(name);
 }
 if (url == null) {
     url = findResource(name);
 }
 return url;
    }
```

```
其中url.openStream()打开Stream，具体如下：
```

```
public final InputStream openStream() throws java.io.IOException {
 return openConnection().getInputStream();
}
```

 

好吧，我承认一看到openConnection就想到JDBC了。其实吧，资源啥的我也不太了解。看看getSystemResource

```
public static URL getSystemResource(String name) {
	ClassLoader system = getSystemClassLoader();
	if (system == null) {
	    return getBootstrapResource(name);
	}
	return system.getResource(name);
    }
```

 

就是首先获取SystemClassLoader，如果失败，则去找BootstrapResource  谁让BootstrapLoader是老大呢。

底层是调用了这个方法获取资源的。

```
static URLClassPath getBootstrapClassPath() {
        return sun.misc.Launcher.getBootstrapClassPath();
    }
```

 bak1：此处就引发了ClassLoader的加载机制，放在下篇学习。

 

角色之二：Class

中午吃饭的时候还和同事讨论ClassLoader的一些东西，暂时先看下Class吧

```
public InputStream getResourceAsStream(String name) {
        name = resolveName(name);
        ClassLoader cl = getClassLoader0();
        if (cl==null) {
            // A system class. 有的class是没有loader的，so this nei~~
            return ClassLoader.getSystemResourceAsStream(name);
        }
        return cl.getResourceAsStream(name);
    }
```

 resolved完成path后，依然是由ClassLoader去处理，此处莫非是代理模式，我日，设计模式离我这么遥远吗？？

bak2：此处就引发了设计模式，放在下篇学习

 

总结：其实我想说的是，萝卜青菜，各有所爱，不是不爱，是吃饱了