zoukankan      html  css  js  c++  java
  • 从jar中读取资源文件的问题

    在项目中遇到了一个问题,在IDE中读取配置文件的程序,打成架包以后,放到服务器上跑,报找不到资源文件的错误。

    其中,资源文件的路径如下:

    获取配置文件路径和读取的方法如下:

    private static String getPath(){
    String path = ModuleFactory.class.getResource("/pipesconfig/").getFile();
    return path;
    }

    private static String readAllText(String fileName) {
    File file = new File(fileName);
    StringBuilder result = new StringBuilder();

    BufferedReader reader = null;
    try {
    reader = new BufferedReader(new FileReader(file));
    String tempString = null;
    while ((tempString = reader.readLine()) != null) {
    result.append(tempString);
    }
    reader.close();
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (reader != null) {
    try {
    reader.close();
    } catch (IOException e1) {
    }
    }
    }

    String resultStr = result.toString();
    int idx = resultStr.indexOf("<");
    resultStr = resultStr.substring(idx);
    return resultStr;
    }
    上述代码,打包以后在服务器上跑,报错如下:

    开始以为是路径写的有问题,或者是Windows系统和Linux系统的问题,按网上的一些建议进行了修改,也没有效果。

    后来,在一篇博客中看到,原来问题出现在读取文件的方式,在jar包内不能使用new File的方式读取jar内的资源文件。因为上述路径并不是文件资源定位符的格式

    (jar中资源有其专门的URL形式: jar:<url>!/{entry} )。所以,如果jar包中的类源代码用File f=new File(相对路径);的形式,是不可能定位到文件资源的。

    这也是为什么源代码1打包成jar文件后,调用jar包时会报出FileNotFoundException的症结所在了。因此,需要修改读取jar内资源文件的方式,具体如下:

    private static String readAllText(String fileName) {

    InputStream is=ModuleFactory.class.getClassLoader().getResourceAsStream(fileName);
    BufferedReader reader=new BufferedReader(new InputStreamReader(is));

    StringBuilder result = new StringBuilder();

    try {
    String tempString = null;
    while ((tempString = reader.readLine()) != null) {
    result.append(tempString);
    }
    reader.close();
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (reader != null) {
    try {
    reader.close();
    } catch (IOException e1) {
    }
    }
    }

    String resultStr = result.toString();
    int idx = resultStr.indexOf("<");
    resultStr = resultStr.substring(idx);
    return resultStr;
    }
    这样程序就可以正常运行了,问题解决。可以参考这篇博客:http://blog.sina.com.cn/s/blog_5f3d71430100ww8t.html

    
    
  • 相关阅读:
    05-3. 六度空间 (PAT)
    05-2. Saving James Bond
    05-1. List Components (PAT)
    04-3. Huffman Codes (PAT)
    04-2. File Transfer (PAT)
    04-1. Root of AVL Tree (PAT)
    03-3. Tree Traversals Again (PAT)
    03-2. List Leaves (PAT)
    03-1. 二分法求多项式单根(PAT)
    CDH Namenode自动切换(active-standby)
  • 原文地址:https://www.cnblogs.com/junjiang3/p/7339786.html
Copyright © 2011-2022 走看看