getResource()和getResourceAsStream以及路径问题【转】【补】

 一 getResource

用JAVA获取文件,听似简单,但对于很多像我这样的新人来说,还是掌握颇浅,用起来感觉颇深,大常最经常用的,就是用JAVA的File类,如要取得c:/test.txt文件,就会这样用File file = new File("c:/test.txt");这样用有什么问题,相信大家都知道,就是路径硬编码,对于JAVA精神来说,应用应该一次成型,到处可用,并且从现实应用来讲,最终生成的应用也会部署到Windows外的操作系统中,对于linux来说,在应用中用了c:/这样的字样,就是失败,所以,我们应该尽量避免使用硬编码,即直接使用绝对路径。

 

  在Servlet应用中,有一个getRealPath(String str)的方法,这个方法尽管也可以动态地获得文件的路径,不必直接手写绝对路径,但这也是一个不被建议使用的方法,那么,我们有什么方法可以更好地获得文件呢?

 

      那就是Class.getResource()与Class.getResourceAsStream()方法,但很多人还是不太懂它的用法,因为很多人(比如不久前的我)都不知道应该传怎么样的参数给它,当然,有些人己经用得如火纯青,这些人是不需要照顾的,在此仅给不会或者还不是很熟的人解释一点点。

 

比如我们有以下目录

|--project

    |--src

        |--javaapplication

            |--Test.java

            |--file1.txt

        |--file2.txt

    |--build 

        |--javaapplication

            |--Test.class

            |--file3.txt

        |--file4.txt

 

在上面的目录中,有一个src目录,这是JAVA源文件的目录,有一个build目录,这是JAVA编译后文件(.class文件等)的存放目录

那么,我们在Test类中应该如何分别获得

file1.txt  file2.txt  file3.txt  file4.txt这四个文件呢?

 

首先讲file3.txt与file4.txt

file3.txt:

//方法一:
File file3 = new File(Test.class.getResource("file3.txt").getFile());

//方法二:
File file3 = new File(Test.class.getResource("/javaapplication/file3.txt").getFile());

//方法三:
File file3 = new File(Test.class.getClassLoader().getResource("javaapplication/file3.txt").getFile());

file4.txt:

//方法一:
File file4 = new File(Test.class.getResource("/file4.txt").getFile());

//方法二:
File file4 = new File(Test.class.getClassLoader().getResource("file4.txt").getFile());

 

很好,我们可以有多种方法选择,但是file1与file2文件呢?如何获得?

答案是,你只能写上它们的绝对路径,不能像file3与file4一样用class.getResource()这种方法获得,它们的获取方法如下

假如整个project目录放在c:/下,那么file1与file2的获取方法分别为

file1.txt

//方法一:
File file1 = new File("c:/project/src/javaapplication/file1.txt");

//方法二:。。。没有

file2.txt

//方法一:
File file2 = new File("c:/project/src/file2.txt");

//方法二:。。。也没有

总结一下:

  就是你想获得文件,你得从最终生成的.class文件为着手点,不要以.java文件的路径为出发点,因为真正使用的就是.class,不会拿个.java文件就使用,因为java是编译型语言嘛。

  至于getResouce()方法的参数,你以class为出发点,再结合相对路径的概念,就可以准确地定位资源文件了,至于它的根目录嘛,你用不同的IDE build出来是不同的位置下的,不过都是以顶层package作为根目录,比如在Web应用中,有一个WEB-INF的目录,WEB-INF目录里面除了web.xml文件外,还有一个classes目录,没错了,它就是你这个WEB应用的package的顶层目录,也是所有.class的根目录“/”,假如classes目录下面有一个file.txt文件,它的相对路径就是"/file.txt",如果相对路径不是以"/"开头,那么它就是相对于.class的路径

  还有一个getResourceAsStream()方法,它相当于你用getResource()取得File文件后,再new InputStream(file)一样的结果.

二 getResourceAsStream

java路径问题(一)——getClass().getResourceAsStream()

转自--->http://ouyangfei0426.iteye.com/blog/1020232
src(源文件夹)

┣━11.properties

┗━myspider(myspider包)
         ┃
         ┣━22.properties
         ┗━Test.java

import java.io.UnsupportedEncodingException;  
  
/** 
 * 
 * @author mark 
 */  
public class Test {  
    public static void main(String[] args) throws UnsupportedEncodingException{  
        Test t=new Test();  
        //文件名前不加“/”,则表示从当前类所在的包下查找该资源。如下则表示的是从包myspider下查找22.properties文件资源。  
        System.out.println("1:"+t.getClass().getResourceAsStream("22.properties"));//输出java.io.BufferedInputStream@61de33  
  
        //文件名前加了“/”,则表示从类路径下也就是从classes文件夹下查找资源,如下表示从classes文件夹下查找22.properties文件资源。  
        System.out.println("2:"+t.getClass().getResourceAsStream("/22.properties"));//输出null  
  
        //文件名前加了“/”,则表示从类路径下也就是从classes文件夹下查找资源,如下表示从classes文件夹下查找11.properties文件资源。  
        System.out.println("3:"+t.getClass().getResourceAsStream("/11.properties"));//输出java.io.BufferedInputStream@14318bb  
        System.out.println();  
  
        //当前包路径4:file:/E:/myobject/myspider/build/classes/myspider/  
        System.out.println("4:"+t.getClass().getResource(""));  
  
        //输出当前类路径5:file:/E:/myobject/myspider/build/classes/  
        System.out.println("5:"+t.getClass().getResource("/"));  
    
    }  
}

三 Properties

 properties读取三种方式 及 getResourceAsStream("xxx")路径问题

package a.b;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import a.b.c.Third;

public class Second {
    public static void main(String[] args) {
//        getClassLoader();
//        getResourceAsStream();
        fileInputStream();
    }
    
    public static void getClassLoader(){
        Properties prop = new Properties();
        InputStream inStream = null;
        try {
//             OK,"/"代表了ClassPath根目录,path不能用"/"开头,最终是由ClassLoader获取资源
//                    总之Third.class.getClassLoader()一般都是从classes下直接开始的. 记住getClassLoader(不要从/开始就好了)
            inStream = Third.class.getClassLoader().getResourceAsStream("config.properties");
            prop.load(inStream);
            System.out.println(prop.getProperty("username"));
            System.out.println(prop.getProperty("password"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void getResourceAsStream() {
        Properties prop = new Properties();
        InputStream inStream = null;
        try {
//            都是从当前类的目录下开始获取
//             OK
//            inStream = Second.class.getResourceAsStream("config.properties"); 
            
//             OK,没有"/"就代表从当前目录开始
            inStream = Second.class.getResourceAsStream("c/config.properties"); 
            
//             OK,"/"代表了ClassPath根目录,path可以用"/"开头,最终是由ClassLoader获取资源
//            inStream = Second.class.getResourceAsStream("/a/b/c/config.properties");
            prop.load(inStream);
            System.out.println(prop.getProperty("username"));
            System.out.println(prop.getProperty("password"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void fileInputStream(){
        Properties prop = new Properties();
        InputStream inStream = null;
        try {
            //只能用绝对路径,不能用相对...晕
            inStream = new FileInputStream("D://config.properties"); 
            prop.load(inStream);
            System.out.println(prop.getProperty("username"));
            System.out.println(prop.getProperty("password"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}

总结 :getResourceAsStream读取的文件路径只局限在工程的源文件夹中,包括在工程src根目录下,以及类包里面任何位置,但是如果配置文件路径是在除了源文件夹之外的其他文件夹中时,该方法是用不了的。

 其它

System.getProperties().getProperty("java.io.tmpdir"); //java.io.tmpdir为系统自带临时目录C:\Users\King\AppData\Local\Temp\
this.getClass().getClassLoader().getResource("/").getPath().split("WEB-INF")[0]+"template/";//  可以得到WEB-INF路径

引用自: 心碎逍遥的博客 http://blog.sina.com.cn/s/blog_4b5bc0110100g22w.html 讲得非常清楚,很值得一看.

部分参考自:  http://www.cnblogs.com/linjiqin/archive/2011/02/14/1954647.html

其它未引用,但讲得好的网址: http://blog.csdn.net/wjl_mgqs/article/details/7554741

 

感觉空虚寂寞,只是因为你无所关注,无处付出。
原文地址:https://www.cnblogs.com/whatlonelytear/p/4499530.html