Javaã®ãªã½ã¼ã¹ãã¼ã¿ (1)
Javaã®ãªã½ã¼ã¹ãã¼ã¿ã«é¢é£ããäºæããä½åãã«åãã¦ã¡ã¢ãã¾ãããã®è¨äºã¯å人çãªã¡ã¢ã§ãã
ä»åã¯ããªã½ã¼ã¹ãã¼ã¿ã®åå¾ã«ä½¿ãã¡ã½ããã®ä½¿ç¨æ³ã«ã¤ãã¦æ¸ãã¾ãã
åå: -
次å: id:simply-k:20100719:1279499319
ç®æ¬¡: id:simply-k:20100728:1280299110
ãªã½ã¼ã¹ãã¼ã¿ã®åå¾ã«ãã使ãã¯ã©ã¹ã¨ã¡ã½ãã
ã¯ã©ã¹ | ã¡ã½ãã | æ»ãå¤ |
---|---|---|
Class | getResource(String name) | URL |
Class | getResourceAsStream(String name) | InputStream |
ClassLoader | getResource(String name) | URL |
ClassLoader | getResourceAsStream(String name) | InputStream |
ãªã½ã¼ã¹åã®æå®æ¹æ³ (Classã¯ã©ã¹ã®ã¡ã½ããã使ãå ´å)
- æ¡ä»¶
- Classã¯ã©ã¹ã¯ãjp.co.fooãããã±ã¼ã¸ã®ã¯ã©ã¹ãHogeãã®ã¯ã©ã¹ãªãã©ã«
(jp.co.foo.Hoge.class) - ãªã½ã¼ã¹ãã¼ã¿ã¯ããjp.co.foo.barãããã±ã¼ã¸ã®ãresource.txtã
- Classã¯ã©ã¹ã¯ãjp.co.fooãããã±ã¼ã¸ã®ã¯ã©ã¹ãHogeãã®ã¯ã©ã¹ãªãã©ã«
- ãªã½ã¼ã¹åã®æå®æ¹æ³
- /jp/co/foo/bar/resource.txt (絶対æå®)
- bar/resource.txt (ç¸å¯¾æå®)
- åè
- ç¸å¯¾æå®ã§ã¯ãå
é ã«ã./ããä»ãã¦ã¯ãããªãã
(Jarãã¡ã¤ã«åããå ´åã«ã¨ã©ã¼ã¨ãªãããã) - å
é¨çã«ãClassLoaderã¯ã©ã¹ã®ã¡ã½ãããå¼ã°ããã
ãã®éããªã½ã¼ã¹åã¯ãjp/co/foo/bar/resource.txtãã®ããã«å¤æãããã - ã¯ã©ã¹ãã¼ãã¯å¿ ãããã·ã¹ãã ã¯ã©ã¹ãã¼ãã¨ã¯éããªãã®ã§æ³¨æããã
- ç¸å¯¾æå®ã§ã¯ãå
é ã«ã./ããä»ãã¦ã¯ãããªãã
ãªã½ã¼ã¹åã®æå®æ¹æ³ (ClassLoaderã¯ã©ã¹ã®ã¡ã½ããã使ãå ´å)
- æ¡ä»¶
- Classã¯ã©ã¹ã®å ´åã¨åã
- ãªã½ã¼ã¹åã®æå®æ¹æ³
- jp/co/foo/bar/resource.txt
- åè
- ãªã½ã¼ã¹åã®å é ã«ã/ããä»ãã¦ã¯ãããªãã
- ç¸å¯¾æå®ã¯ã§ããªãã
- ã¯ã©ã¹ãã¼ãã¯å¿ ãããã·ã¹ãã ã¯ã©ã¹ãã¼ãã¨ã¯éããªãã®ã§æ³¨æããã
URLãªãã¸ã§ã¯ãããInputStreamãªãã¸ã§ã¯ããåå¾ããæé
URL url = loader.getResource(resourceName); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream();
InputStreamãªãã¸ã§ã¯ããããã¼ã¿ãåå¾ããä¾
//ããããã£ãã¡ã¤ã«(é常)ã®å ´å InputStream is = Hoge.class.getResourceAsStream(resourceName); Properties props = new Properties(); props.load(is);
//ããããã£ãã¡ã¤ã«(XML)ã®å ´å InputStream is = Hoge.class.getResourceAsStream(resourceName); Properties props = new Properties(); props.loadFromXML(is);
//ããã¹ããã¡ã¤ã«ã®å ´å InputStream is = Hoge.class.getResourceAsStream(resourceName); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; while((line = reader.readLine()) != null){ ... }
URLãªãã¸ã§ã¯ããããã¼ã¿ãåå¾ããä¾
//ç»åãã¡ã¤ã«ã®å ´å (java.awt.Toolkitã使ã) URL url = Hoge.class.getResource(resourceName); Image img = Toolkit.getDefaultToolkit().getImage(url);
åå: -
次å: id:simply-k:20100719:1279499319
ç®æ¬¡: id:simply-k:20100728:1280299110