Java学习篇之---getResource()和getResourceAsStream()

来源:互联网 发布:淘宝全屏店招安装 编辑:程序博客网 时间:2024/06/05 08:15
getResource()和getResourceAsStream()
编译后的Java类文件可以打包成一个jar文件随处运行。但是当我们需要使用一些资源如:一幅图像,一段音频时,就需要在jar包外带有一个资源文件夹,必须保证jar包和资源文件夹一起发布否则程序就不能正常运行。我们希望的是只发布一个jar包,把资源均包含在内。为此我们需要读取资源文件:
利用Java提供的两个函数URL Class.getResource()和InputStream Class.getResourceAsStream()。
这里只着重介绍函数URL Class.getResource(),函数InputStream Class.getResourceAsStream()与之类似。
我的项目结构如下:

文件version.properties存放位置如下:

代码如下:package com.ryze.work.component;public class MainFrame {//public static final String VERSION_PROPERTIES_FILENAME = "/version.properties";public static final String VERSION_PROPERTIES_FILENAME = "version.properties";public static void main(String[] args) throws Exception{MainFrame mainFrame = new MainFrame();mainFrame.test();}public void test(){java.net.URL versionPropertiesURL = this.getClass().getResource(VERSION_PROPERTIES_FILENAME);System.out.println(versionPropertiesURL);}}
运行结果如下:

当用代码        public static final String VERSION_PROPERTIES_FILENAME = "/version.properties";替换掉public static final String VERSION_PROPERTIES_FILENAME = "version.properties";
则需要将文件version.properties放到如下路径:



1 0