无法在runnable jar

时间:2016-07-20 14:23:20

标签: java properties java-6 eclipse-indigo

我正在研究java中的一个小项目。使用的版本是带有eclipse Indigo的JRE6。

应用程序似乎工作正常,但是当我想执行这个api的runnable jar时,它不起作用。 所以我用c执行我的jar:... \ jr6 \ bin \ java.exe -jar c:\ User \ Olivier \ Desktop \ appli.jar

然后第一个问题是关于两个罐子我必须反转以使它们起作用。 (2个xstream罐子)

现在,出现一个新错误。似乎应用程序无法加载文件名language.properties

我将它添加到jar中,与其他jar一起放在appli.jar的文件夹中,我也尝试将它添加到清单中。我自己显然无法解决这个问题。

如果有人有想法?

 protected Properties readPropertiesFile(final String filename,final int level){
    if (filename == null) {
        return null;
    }
    //if first level (0) then clear the list of already loaded files
    if (level == 0) {
        this.alreadyLoadedFiles.clear();
    }


    InputStreamReader stream = null;
    try {
        //Try to open a connection with the properties file

        stream = new InputStreamReader(new FileInputStream(filename), "UTF-8");

    } catch (FileNotFoundException e) {
        //Try to find the specified propertie file in Classpath
        this.logServices.severe("Cannot found the '"+filename+"' properties file.");

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        this.logServices.severe("UnsupportedEncodingException '"+filename+"' properties file encoding in UTF-8");
    } 

    //Read the properties file
    Properties props = new Properties();
    try {

            props.load(stream);

        //Add the file in the list of already loaded file
        this.alreadyLoadedFiles.add(filename);

    } catch (Exception e) {
        props = null;
        this.logServices.severe("Cannot read the '"+
                filename+"' properties file : "+e.getMessage());
    } finally {
        try {
            stream.close();
        } catch (IOException e) {
        }
    }
    //Search for the include Tag in properties file
    this.readIncludePropertiesFiles(props, (level+1));
    return props;

1 个答案:

答案 0 :(得分:0)

  

路径名,无论是抽象的还是字符串形式,可以是绝对路径名也可以是相对路径名。绝对路径名是完整的,因为不需要其他信息来定位它表示的文件。相反,相对路径名必须根据从其他路径名获取的信息来解释。

     

默认情况下,java.io包中的类始终解析当前用户目录的相对路径名。此目录由系统属性user.dir命名,通常是调用Java虚拟机的目录。 Source JavaDoc

因此,如果将文件放在jar文件中,则路径可能无法解析,具体取决于运行程序的目录。因此,在类路径中访问文件的更好方法是按如下方式使用它:

InputStream is = this.getClass().getResourceAsStream(filename);
InputStreamReader stream =  new InputStreamReader(is, "UTF-8");

而不是

stream = new InputStreamReader(new FileInputStream(filename), "UTF-8");

Eidt:

以下是如上所述工作的maven项目结构的示例屏幕截图。文件Lexicon.txt将被复制到jar文件的根目录,因此您传递给getResourceAsStream()方法的名称为/Lexicon.txt filename

enter image description here