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

    
    
  • 相关阅读:
    自动化单元测试工具 EvoSuite 的简单使用
    Dialog lookup method
    微软Axapta中PDF支持中文
    Connected to Ax AOS by code
    Dialog control field event
    Find the tables extending a specific extended data type
    sqlplus不使用服务名,直接使用IP地址连接Oracle
    ATL编写的带窗口的控件,无论VC6(ATL3.0) VC7.1(ATL7.0) 在Windows 7 或 Server 2008 下,WinForm调用时发生的问题
    Ice的slice文件自定义编译命令
    VC9 SP1中新增加的标准 C++ 库中的新功能
  • 原文地址:https://www.cnblogs.com/junjiang3/p/7339786.html
Copyright © 2011-2022 走看看