`
流浪鱼
  • 浏览: 1697851 次
  • 性别: 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;
  }

}

 

 

分享到:
评论

相关推荐

    获取程序根目录可执行文件根目录示例

    在Unix/Linux系统中,获取根目录的方法略有不同: 1. **C++ (POSIX)**:可以使用`readlink("/proc/self/exe", buf, sizeof(buf));`获取可执行文件的链接,然后解析得到路径。 2. **Python**: 在Linux上,使用`os....

    JavaWeb_servlet(10)_ 通过 ServletContex 获得根目录下的文件路径

    // 获取根目录的物理路径 String imagePath = rootPath + "images/logo.png"; // 拼接文件路径 ``` `getRealPath("/")`返回的是Web应用的根目录在服务器上的实际路径。这在我们需要读取或写入这些文件时非常有用,...

    java文件路径获取

    - `getClassLoader().getResource("/")`会返回`classpath`的根目录,但`getClassLoader().getResource("/")`是错误的用法,因为这会导致路径解析出错。 #### 七、结论 通过本文的介绍,我们可以了解到Java中获取...

    Java中获取文件路径的几种方式

    例如,通过`this.getClass().getResource()`方法可以获取资源文件的路径。 ##### 示例代码: ```java File f = new File(this.getClass().getResource("/").getPath()); System.out.println(f.getAbsolutePath()); ...

    java中File的相对路径与绝对路径总结

    - **在使用`getResource()`方法时**,如果路径不以`/`开头,则默认是从调用该方法的类的所在位置开始查找,而以`/`开头则表示从类路径的根目录开始查找。 #### 总结 通过以上分析可以看出,在Java中处理文件路径时...

    JAVA获取文件绝对路径的方法

    绝对路径是指文件在文件系统中的完整地址,它包含了从根目录到文件的所有层级。以下是一些在Java中获取文件绝对路径的方法: 1. `File.getAbsolutePath()` `java.io.File` 类提供了 `getAbsolutePath()` 方法,此...

    在Java程序中获取当前运行程序的路径

    首先,我们可以通过`java.lang.Class`类的`getResource`或`getResourceAsStream`方法来获取类路径中的资源文件路径。这两个方法都是在类路径中查找资源,返回一个URL对象,从中可以获取路径信息。例如,如果我们有一...

    java 获取项目文件路径实现方法

    此外,如果你需要获取项目的根目录,特别是对于桌面应用,可以考虑使用`System.getProperty("user.dir")`,这将返回执行Java命令时的工作目录,通常为项目的根目录。在Web应用中,由于类加载机制的不同,这种方法...

    java获取路径的各种方法

    5. **ServletContext.getRealPath()**:在Servlet中,通过ServletContext对象的getRealPath方法,可以获取到Web应用的根目录,这对于读取或写入Web应用内的文件非常有用。 6. **this.getClass().getClassLoader()....

    如何读取webroot文件下的属性文件

    在Servlet容器(如Tomcat)中,`webroot`是应用程序的根目录,可以通过`ServletContext`对象获取。首先,我们需要在Servlet或者Filter中获取`ServletContext`实例: ```java ServletContext context = ...

    获取路径的各种方法

    4. `this.getClass().getClassLoader().getResource("").getPath()`:这个方法适用于任何Java类,无论是在JSP、Servlet还是普通的Java文件中,它能获取到工程的"class"目录下的路径。 5. `request.getParameter("")...

    JAVA中获取各种路径

    此方法返回Web应用的根目录路径,如`E:\Tomcat\webapps\TEST`,这对于获取应用内的任何资源非常关键。 #### (2) 获取完整URL地址:`request.getRequestURL()` 此方法返回完整的URL,包括协议、主机、端口以及上...

    JAVA获取各种路径总结

    - `getServletContext()` 返回当前Servlet的上下文对象,可以从中获取Web应用的根目录路径。 - 可用的方法还包括: - `javax.servlet.http.HttpSession.getServletContext()` - `javax.servlet.jsp.PageContext....

    JAVA如何获取工程下的文件

    `Class.getResource` 方法允许我们通过类对象获取资源文件。这个方法返回一个 `URL` 对象,表示资源的位置。它会根据类路径查找资源,因此资源必须包含在类路径(classpath)中。 #### 示例代码: ```java public ...

    javaweb 读取 classes 下的文件

    本文将详细介绍如何在Java Web环境中读取`classes`目录下的文件。 首先,了解Java Web项目的基本结构是关键。一个标准的Java Web应用通常包含以下几个部分: 1. `WEB-INF`目录:包含Web应用的配置文件,如`web.xml...

    JavaWeb_servlet(11)_ 通过 ServletContex 获得类路径下的文件路径

    1. `getRealPath()`:这个方法返回一个字符串,表示相对于Web应用根目录的类路径资源的实际文件系统路径。例如,如果你有一个配置文件位于`WEB-INF/classes/config.properties`,你可以使用如下的代码来获取其实际...

    JAVA类,JSP,Servlet获取工程路径.txt

    在Java Web开发过程中,经常需要获取项目的根目录或某个特定资源文件的绝对路径。这些路径信息对于加载资源文件、处理文件上传下载等功能至关重要。本文将详细介绍在Eclipse环境中通过JSP、Servlet以及Java类获取...

    总结一下java获取路径几种途径

    使用`Paths.get`方法可以创建一个`Path`对象,然后通过`Path`类提供的方法获取文件的绝对路径、父目录、文件名等信息。 ### 5. 使用系统环境变量 有时候路径可能存储在系统环境变量中,比如`PATH`环境变量包含了...

Global site tag (gtag.js) - Google Analytics