`
流浪鱼
  • 浏览: 1635755 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

获取根目录下的文件方法 Resource

    博客分类:
  • java
 
阅读更多

 

 private static ClassLoader getClassLoader() {
    if (defaultClassLoader != null) {
      return defaultClassLoader;
    } else {
      return Thread.currentThread().getContextClassLoader();
    }
  }

 public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
    InputStream in = null;
    if (loader != null) in = loader.getResourceAsStream(resource);
    if (in == null) in = ClassLoader.getSystemResourceAsStream(resource);
    if (in == null) throw new IOException("Could not find resource " + resource);
    return in;
  }

 使用:

InputStream in = ClassLoader.getSystemResourceAsStream("1004.xml");

 

 

/*
 *  Copyright 2004 Clinton Begin
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.ibatis.common.resources;

import com.ibatis.common.beans.ClassInfo;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Properties;

/**
 * A class to simplify access to resources through the classloader.
 */
public class Resources extends Object {

  private static ClassLoader defaultClassLoader;
  
  /**
   * Charset to use when calling getResourceAsReader.
   * null means use the system default.
   */
  private static Charset charset;

  private Resources() {
  }

  /**
   * Returns the default classloader (may be null).
   *
   * @return The default classloader
   */
  public static ClassLoader getDefaultClassLoader() {
    return defaultClassLoader;
  }

  /**
   * Sets the default classloader
   *
   * @param defaultClassLoader - the new default ClassLoader
   */
  public static void setDefaultClassLoader(ClassLoader defaultClassLoader) {
    Resources.defaultClassLoader = defaultClassLoader;
  }

  /**
   * Returns the URL of the resource on the classpath
   *
   * @param resource The resource to find
   * @return The resource
   * @throws IOException If the resource cannot be found or read
   */
  public static URL getResourceURL(String resource) throws IOException {
    return getResourceURL(getClassLoader(), resource);
  }

  /**
   * Returns the URL of the resource on the classpath
   *
   * @param loader   The classloader used to load the resource
   * @param resource The resource to find
   * @return The resource
   * @throws IOException If the resource cannot be found or read
   */
  public static URL getResourceURL(ClassLoader loader, String resource) throws IOException {
    URL url = null;
    if (loader != null) url = loader.getResource(resource);
    if (url == null) url = ClassLoader.getSystemResource(resource);
    if (url == null) throw new IOException("Could not find resource " + resource);
    return url;
  }

  /**
   * Returns a resource on the classpath as a Stream object
   *
   * @param resource The resource to find
   * @return The resource
   * @throws IOException If the resource cannot be found or read
   */
  public static InputStream getResourceAsStream(String resource) throws IOException {
    return getResourceAsStream(getClassLoader(), resource);
  }

  /**
   * Returns a resource on the classpath as a Stream object
   *
   * @param loader   The classloader used to load the resource
   * @param resource The resource to find
   * @return The resource
   * @throws IOException If the resource cannot be found or read
   */
  public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
    InputStream in = null;
    if (loader != null) in = loader.getResourceAsStream(resource);
    if (in == null) in = ClassLoader.getSystemResourceAsStream(resource);
    if (in == null) throw new IOException("Could not find resource " + resource);
    return in;
  }

  /**
   * Returns a resource on the classpath as a Properties object
   *
   * @param resource The resource to find
   * @return The resource
   * @throws IOException If the resource cannot be found or read
   */
  public static Properties getResourceAsProperties(String resource)
      throws IOException {
    Properties props = new Properties();
    InputStream in = null;
    String propfile = resource;
    in = getResourceAsStream(propfile);
    props.load(in);
    in.close();
    return props;
  }

  /**
   * Returns a resource on the classpath as a Properties object
   *
   * @param loader   The classloader used to load the resource
   * @param resource The resource to find
   * @return The resource
   * @throws IOException If the resource cannot be found or read
   */
  public static Properties getResourceAsProperties(ClassLoader loader, String resource)
      throws IOException {
    Properties props = new Properties();
    InputStream in = null;
    String propfile = resource;
    in = getResourceAsStream(loader, propfile);
    props.load(in);
    in.close();
    return props;
  }

  /**
   * Returns a resource on the classpath as a Reader object
   *
   * @param resource The resource to find
   * @return The resource
   * @throws IOException If the resource cannot be found or read
   */
  public static Reader getResourceAsReader(String resource) throws IOException {
    Reader reader;
    if (charset == null) {
      reader = new InputStreamReader(getResourceAsStream(resource));
    } else {
      reader = new InputStreamReader(getResourceAsStream(resource), charset);
    }
    
    return reader;
  }

  /**
   * Returns a resource on the classpath as a Reader object
   *
   * @param loader   The classloader used to load the resource
   * @param resource The resource to find
   * @return The resource
   * @throws IOException If the resource cannot be found or read
   */
  public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {
    Reader reader;
    if (charset == null) {
      reader = new InputStreamReader(getResourceAsStream(loader, resource));
    } else {
      reader = new InputStreamReader(getResourceAsStream(loader, resource), charset);
    }
    
    return reader;
  }

  /**
   * Returns a resource on the classpath as a File object
   *
   * @param resource The resource to find
   * @return The resource
   * @throws IOException If the resource cannot be found or read
   */
  public static File getResourceAsFile(String resource) throws IOException {
    return new File(getResourceURL(resource).getFile());
  }

  /**
   * Returns a resource on the classpath as a File object
   *
   * @param loader   - the classloader used to load the resource
   * @param resource - the resource to find
   * @return The resource
   * @throws IOException If the resource cannot be found or read
   */
  public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException {
    return new File(getResourceURL(loader, resource).getFile());
  }

  /**
   * Gets a URL as an input stream
   *
   * @param urlString - the URL to get
   * @return An input stream with the data from the URL
   * @throws IOException If the resource cannot be found or read
   */
  public static InputStream getUrlAsStream(String urlString) throws IOException {
    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    return conn.getInputStream();
  }

  /**
   * Gets a URL as a Reader
   *
   * @param urlString - the URL to get
   * @return A Reader with the data from the URL
   * @throws IOException If the resource cannot be found or read
   */
  public static Reader getUrlAsReader(String urlString) throws IOException {
    return new InputStreamReader(getUrlAsStream(urlString));
  }

  /**
   * Gets a URL as a Properties object
   *
   * @param urlString - the URL to get
   * @return A Properties object with the data from the URL
   * @throws IOException If the resource cannot be found or read
   */
  public static Properties getUrlAsProperties(String urlString) throws IOException {
    Properties props = new Properties();
    InputStream in = null;
    String propfile = urlString;
    in = getUrlAsStream(propfile);
    props.load(in);
    in.close();
    return props;
  }

  /**
   * Loads a class
   *
   * @param className - the class to load
   * @return The loaded class
   * @throws ClassNotFoundException If the class cannot be found (duh!)
   */
  public static Class classForName(String className) throws ClassNotFoundException {
    Class clazz = null;
    try {
      clazz = getClassLoader().loadClass(className);
    } catch (Exception e) {
      // Ignore.  Failsafe below.
    }
    if (clazz == null) {
      clazz = Class.forName(className);
    }
    return clazz;
  }

  /**
   * Creates an instance of a class
   *
   * @param className - the class to create
   * @return An instance of the class
   * @throws ClassNotFoundException If the class cannot be found (duh!)
   * @throws InstantiationException If the class cannot be instantiaed
   * @throws IllegalAccessException If the class is not public, or other access problems arise
   */
  public static Object instantiate(String className)
      throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    return instantiate(classForName(className));
  }

  /**
   * Creates an instance of a class
   *
   * @param clazz - the class to create
   * @return An instance of the class
   * @throws InstantiationException If the class cannot be instantiaed
   * @throws IllegalAccessException If the class is not public, or other access problems arise
   */
  public static Object instantiate(Class clazz) throws InstantiationException, IllegalAccessException {
    try {
      return ClassInfo.getInstance(clazz).instantiateClass();
    } catch (Exception e) {
      // Try alternative...theoretically should fail for the exact same
      // reason, but in case of a weird security manager, this will help
      // some cases.
      //return clazz.newInstance();
      return clazz.newInstance();
    }
  }

  private static ClassLoader getClassLoader() {
    if (defaultClassLoader != null) {
      return defaultClassLoader;
    } else {
      return Thread.currentThread().getContextClassLoader();
    }
  }

  public static Charset getCharset() {
    return charset;
  }

  /**
   * Use this method to set the Charset to be used when
   * calling the getResourceAsReader methods.  This will
   * allow iBATIS to function properly when the system default
   * encoding doesn't deal well with unicode (IBATIS-340, IBATIS-349)
   * 
   * @param charset
   */
  public static void setCharset(Charset charset) {
    Resources.charset = charset;
  }

}

 

 

分享到:
评论

相关推荐

    SpringBoot页面跳转访问css、js等静态资源引用无效解决.docx

    解释:SpringBoot项目默认访问根目录有三个分别是: /resources :系统默认的根路径 /static :所有静态资源文件如js、css、jpg、html等文件是可以直接访问的 /templates :此目录下的文件是不可以直接访问的,需要...

    自定义图片资源编辑器

    将 Photograph resource.dll,LOADing.dll,GET_RESX.dll,formdll.dll,Simplicit.Net.Lzo.dll,lzo.dll全部拷贝到软件根目录,在项目总引用Photograph resource.dll 在对应软件根目录中建立DATA文件夹,将资源文件...

    ASP.NET的网页代码模型及生命周期

    q 不需要项目文件,可以把一个目录当作一个Web应用来处理。 总体来说,ASP.NET网站适用于较小的网站开发,因为其动态编译的特点,无需整站编译。而ASP.NET应用程序适应大型的网站开发、维护等。 4.2 代码隐藏页模型...

    php_htmlWebpackPlugin:不同 PHP 项目移植的 webpack 配置,适合仅使用 PHP 路由,支持版本号和走接口获取数据的前端项目

    这是一份可以快速在不同 PHP 项目移植的 webpack 配置,适合仅使用 PHP 路由,...打包前的 src 文件在项目根目录: src |_assets |_css |_*.css |_js |_*.js |_*.html // 模版文件 在这里使用 webpack + html-w

    Java获取*路径实现探讨

    (1)、request.getRealPath(“/”);//不推荐使用获取工程的根路径 (2)、...//获取工程的根路径,这个方法比较好用,可以直接在servlet和jsp中使用 (4)、 this.getClass().getClassLoader().getResource(“”).getPath();

    cms后台管理

    5.classes下有四个文件,手动烤到myeclipse项目src根目录下中 6.将服务器上jeecms项目删掉,发布新建的jeecms项目。 三 首页的加载过程 在浏览器中输入http://localhost:8080/jeecms,回车 首先进入配置文件web....

    基于Java开发的员工考勤管理系统源码-Web版+数据库sql+项目说明+设计报告.zip

    3. 修改 `src/resource/application-dev.yml` 文件下的 `spring.datasource.username` 与 `spring.datasource.password` 字段为自己本地 MySQL 的用户名与密码。 4. 运行 `DemoApplication.java`,项目运行在 8080 ...

    my-ride-history:一个兴趣爱好项目,用于在地图上显示Strava中记录的游乐设施。 还计算访问的图块,最大图块簇和最大图块平方

    您需要在项目根目录下创建conf.py配置文件。 示例文件可能如下所示: # Basic auth username, protects ride data sync related resources auth_username = 'my username' # Basic auth password, protects ride ...

    HGE_系列教材(1-9)

    1. 下载完HGE 之后,需要使用到lib\vc 文件夹下的库文件以及include 目录下的头文 件 2. 打开 Tools->Options->Directories 如上两图,添加路径 3. 在游戏开发中使用HGE 首先建立一个空的Win32 工程,然后选择...

    SpringMVC-Mybatis-Shiro-redis-master 权限集成缓存中实例

    * 所以这里替换了一下,使用根目录开始的URI */ String uri = httpRequest.getRequestURI();//获取URI String basePath = httpRequest.getContextPath();//获取basePath if(null != uri && uri.startsWith...

    azure-rest-api-specs:Microsoft Azure的REST API规范的来源

    Azure REST API规范 ...'resource-manager'和'data-plane'文件夹:RP可以将规范归为以下两类之一: resource-manager (用于ARM资源)和data-plane (用于其他所有内容)。 RP的readme.md配置文件( readme.md

    mahara教师评价系统

    作为网站根目录的一个子目录 3.在 mysql 里面见一个新数据库,字符集选择 utf-8。 4.复制 mahara 目录下的 config-dist.php 文件为 config.php。并修改其中的配置,指定 mysql 用户名,密码,数据库名,其余的不用改...

    精通AngularJS part1

    根目录52 进入源代码目录54 AngularJS的特定文件54 轻装上路56 深入测试目录57 文件命名约定57 24AngularJS模块和文件57 一个文件,一个模块58 模块内部59 注册provider的不同语法59 声明配置和运行块的...

    仿世纪佳缘婚介交友系统5.3 ASP+SQL

    当选择水印图片,那么[添加水印LOGO图片地址]需要正确输入图片的地址(必须以根目录为起点的路径) 、远程抓取即为会员相册可以通过其它网站上的图片地址,系统会抓取该图片并保存到空间中!  (9)验证码设置...

    新版Android开发教程.rar

    ----------------------------------- Android 编程基础 1 封面----------------------------------- Android 编程基础 2 开放手机联盟 --Open --Open --Open --Open Handset Handset Handset Handset Alliance ...

    zookeeper淘宝实现的监控

    目前开源世界中暂没有一个...3. 到taokeeper根目录下执行 packageDaily.cmd 命令,打成一个war包,之后进行部署 如何使用 1. taokeeper-monitor启动后,还没有配置任何zookeeper集群,点击“加入监控”进行集群添加。

    ZendFramework中文文档

    设置文件根目录 7.1.2.3. 创建URL重写规则 7.1.2.4. 创建你的bootstrap文件 7.1.2.5. 创建默认的控制器(Action Controller) 7.1.2.6. 创建你的视图脚本 7.1.2.7. 创建你自己的错误控制器 7.1.2.8. 访问站点...

    oracle学习文档 笔记 全面 深刻 详细 通俗易懂 doc word格式 清晰 连接字符串

     删除HKEY_CLASSES_ROOT目录下所有以Ora、Oracle、Orcl或EnumOra为前缀的键。  删除HKEY_CURRENT_USER/SOFTWARE/Microsoft/windows/CurrentVersion/Explorer/MenuOrder/Start Menu/Programs中所有以oracle 开头...

    Eclipse权威开发指南2.pdf

    1.4 获取与安装Eclipse.. 11 1.5 本章小结...... 11 1.6 参考文献...... 12 第2章 Eclipse入门 13 2.1 第一步...... 14 2.1.1 提示没有任何JRE可用的对话框..... 14 2.1.2 创建您的第一个项目..... 15 2.1.3 ...

    Eclipse权威开发指南3.pdf

    1.4 获取与安装Eclipse.. 11 1.5 本章小结...... 11 1.6 参考文献...... 12 第2章 Eclipse入门 13 2.1 第一步...... 14 2.1.1 提示没有任何JRE可用的对话框..... 14 2.1.2 创建您的第一个项目..... ...

Global site tag (gtag.js) - Google Analytics