我已经将自己的class和resource,property文件都放到jar里面了。我用
getClass().getResource( "resources/config.xml" ); 
或者getClass().getResource( "/resources/config.xml" ); 
返回都是null。到底怎么取得路径。PS:不在jar里是好的。

解决方案 »

  1.   

    查找到了String currentJarPath = URLDecoder.decode(YourClassName.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8"); //获取当前Jar文件名
    java.util.jar.JarFile currentJar = new java.util.jar.JarFile(currentJarPath);
    java.util.jar.JarEntry dbEntry = currentJar.getJarEntry("包名/dbSelect.xml");
    InputStream in = currentJar.getInputStream(dbEntry);
    //以上YourClassName是class全名,也就是包括包名
      

  2.   

    提供一个静态方法:
    // Get content from file in jar
        public static String getTextFromJar(String s, Class class1) {
            String s1 = "";
            InputStream inputstream = class1.getResourceAsStream(s);        if (inputstream != null) {
                BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(
                            inputstream));
                String s2;            try {
                    while ((s2 = bufferedreader.readLine()) != null) {
                        s1 = s1 + s2;
                    }
                } catch (IOException ioexception) {
                    ioexception.printStackTrace();
                }
            }        return s1;
        }