天天看点

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包)

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

       |                         |——system.bat

       |                         |——background.png

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

                                 |——system.bat

                                 |——background.png

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

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

  ImageIcon im = new ImageIcon(imUrl);

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

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

ImageIcon im = new ImageIcon(imgUrl);

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

本文转自博客园沉睡森林@漂在北京的博客,原文链接:Java或者JAR包获取读取资源文件的路径的问题总结,如需转载请自行联系原博主。