Java或者JAR包获取读取资源文件的路径的问题总结

这里分为具体两种: 

第一种:资源文件为一般后缀文件 

第二种:资源文件为图片文件 

【NO1】第一种 

  使用这行代码可以获取class类的根目录的路径 

  String path =Thread.currentThread().getContextClassLoader().getResource("").getPath(); 

例子:我用的开发软件MyEclipse 6.5 

假设项目文件夹如下: 

   files———bin——core(生成class包) 

       |               |         |——Main.class(生成的class文件) 

       |               | 

       |               |——resource( 生成资源文件夹) 

       |                         |——a.bat 

       |                         |——b.png 

       |———src——core(源包)  

                   |             |—— Main.java(源代码) 

                   | 

                   |——resource(源资源文件夹)  

                                 |——a.bat 

                                 |——b.png 

//源代码Main.java 

//============================================================ 

package core; 
import java.io.File; 

public class Main { 


    public static void main(String[] args){ 
        try{ 
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();    //添加 
        File af=new File(path+"/resource"); 
        if(!af.exists()) System.out.println("nullEXIST");; 
        String[] files =af.list(); 
        if(files.length==0) System.out.println("nullLENGTH");; 
        for(int i=0;i<files.length;i++){ 
            if(files[i]!=null)System.out.println(files[i]); 
            else System.out.println("null"); 
        } 
        
        } 
        catch(Exception e){ 
            System.out.println("HugeERROR"); 
        } 
    } 
        


// =============================================================== 

    运行结果: 

a.bat 

b.png   

就对了   

【NO2】第二种 

建议使用下面( 2 )方法,因为(1)jar之后可能出现找不到的问题 (之前我试过出现这种情况) 

这里代码省了 

(1)、你将所有资源打包为epm.jar,你的类位于一个包中:package core;你的图片资源全部放在images文件夹中,而images文件夹也位于core包内。这样的话,最终的路径表现为: 
epm———bin——core(生成class包) 

       |               |         |——Main.class(生成的class文件) 

       |               | 

       |               |——images( 生成资源文件夹) 

       |                         |——system.bat 

       |                         |——background.png 

       |———src——core(源包)  

                   |             |—— Main.java(源代码) 

                   | 

                   |——images(源资源文件夹)  

                                 |——system.bat 

                                 |——background.png 




  可以通过相对路径来访问:        

  java.net.URL imUrl = getClass().getResource("images/background.png"); 
  ImageIcon im = new ImageIcon(imUrl); 

(2)、另一种情况,如果你的类有很多,并且包的结构很复杂,应该把图片放到最外层,让所有的类通过绝对路径来访问该图片 

epm———bin——core(生成class包) 

       |               |         |——Main.class(生成的class文件) 

       |               | 

       |               |——images( 生成资源文件夹) 

       |                         |——system.bat 

       |                         |——background.png 

       |———src——core(源包)  

                   |             |—— Main.java(源代码) 

                   | 

                   |——images(源资源文件夹)  

                                 |——system.bat 

                                 |——background.png 


java.net.URL imUrl = getClass().getResource("/images/background.png"); 
ImageIcon im = new ImageIcon(imgUrl); 

区别非常细微,仅仅是在“images”的前面加了一个反斜杠"/",这个反斜杠就表示根目录,没有反斜杠就表示相对路径。 

 

Java中获取资源文件

新建一个Java工程,新建一个constants.properties资源文件

Java代码   收藏代码
  1. userName = snail  
  2. age = 24  
  3. password = 123456  

然后我们再建立一个类Constans.java,附上静态变量

Java代码   收藏代码
  1. package testproperties;  
  2.   
  3. public  class Constants {  
  4.   
  5.     public static String userName;  
  6.     public static int age;  
  7.     public static String password;   
  8. }  

接下来的工作就尝试着如何获取properties文件类定义的姓名、年龄和密码了,新建一个InitProperties类

package testproperties;

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

public class InitProperties {
	  private static final long serialVersionUID = -2106230733190196852L;

	  public void init()
	  {
	    System.out.println("#############################加载配置信息###########################");
	    Properties prop = new Properties();

	    //得到的是编译后的bin的目录Class.class.getClass().getResource("/").getPath();
	    
	    //这个是绝对路径
//	    String filepath = "E:\\myeclipse6\\workspace\\XXX\\src\\testproperties\\constants.properties";
	    
	    String filepath = Class.class.getClass().getResource("/").getPath()+"/testproperties/constants.properties" ;
	  
	    System.out.println("++++++++++++"+Class.class.getClass().getResource("/").getPath()+"+++++++++++++");
	    
	    FileInputStream fis = null;
	    try {
	      fis = new FileInputStream(filepath);
	      prop.load(fis);
	      Constants.userName = prop.getProperty("userName");
	      Constants.age = Integer.parseInt(prop.getProperty("age"));
	      Constants.password = prop.getProperty("password");
	      System.out.println(Constants.userName+Constants.age+Constants.password);;
	      System.out.println("#############################加载配置信息完成###########################");
	    }
	    catch (IOException e) {
	      System.out.println("加载constants.properties文件失败,文件不存在后者路径不正确! ");
	      e.printStackTrace();
	    }
	  }
	  public static void main(String[] args) {
		  InitProperties ip = new InitProperties();
		  ip.init();
	}
}

现在附上集中在jsp、Java、和servlet中获取路径的方法:(引用自http://zhidao.baidu.com/question/86179810.html?fr=qrl&cid=93&index=5

1.jsp中取得路径:

以工程名为TEST为例:

(1)得到包含工程名的当前页面全路径:request.getRequestURI() 
    结果:/TEST/test.jsp 
(2)得到工程名:request.getContextPath() 
    结果:/TEST 
(3)得到当前页面所在目录下全名称:request.getServletPath() 
    结果:如果页面在jsp目录下 /TEST/jsp/test.jsp 
(4)得到页面所在服务器的全路径:application.getRealPath("页面.jsp") 
    结果:D:\resin\webapps\TEST\test.jsp 
(5)得到页面所在服务器的绝对路径:absPath=new java.io.File(application.getRealPath(request.getRequestURI())).getParent(); 
    结果:D:\resin\webapps\TEST

 

2.在类中取得路径:

(1)类的绝对路径:Class.class.getClass().getResource("/").getPath() 
    结果:D:/TEST/WebRoot/WEB-INF/classes/pack/ 
(2)得到工程的路径:System.getProperty("user.dir") 
    结果:D:\TEST

 

3.在Servlet中取得路径:

(1)得到工程目录:request.getSession().getServletContext().getRealPath("") 参数可具体到包名。 
    结果:E:\Tomcat\webapps\TEST 
(2)得到IE地址栏地址:request.getRequestURL() 
    结果:http://localhost:8080/TEST/test 
(3)得到相对地址:request.getRequestURI() 
    结果:/TEST/test


再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自www.cnblogs.com/skiwnchhw/p/10349625.html