java.io.IOException:ストリームは、外部のjarファイルフォルダの設定ファイルにアクセスして閉じました

クラマ :

私は、の設定ファイルの外部からのconfigsを読み込みjarファイルを実行しています/ホーム/ユーザー/ XXX / testFolder / jarファイル、設定ファイルのパスがある/opt/xxx/conf/global_config.cfgを。

私は、エラーが発見されていないファイルが原因であると仮定のでしかし、私は、瓶内のアクセスファイルにできますよ。

以下は、私のコードは次のようになります。

public Properties createProperties(){
    Properties p = null;
    ClassLoader cl = this.getClass().getClassLoader();
    try (InputStream stream = cl.getResourceAsStream("/opt/xxx/conf/global_config.cfg")) {
        p = new Properties();
        BufferedInputStream bis = new BufferedInputStream(stream);
        p.load(bis); // this is throwing the error
        System.out.println(p.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return p;
}

Linuxシステムに関係なく、そのパスのファイルを取得する正しい方法は何ですか?

クリス:
cl.getResourceAsStream("/opt/xxx/conf/global_config.cfg") 

リソースは、クラスの場所に関連して利用できることを期待しています。だから、それはJAR内のクラスへの相対パスとして検索します。しかし、パスは/opt/xxx/conf/global_config.cfg絶対ディスク・パスは、それを読むため、あなたが使用する必要がありますFileInputStream

public Properties createProperties(){
    Properties p = null;
    ClassLoader cl = this.getClass().getClassLoader();
    try (InputStream stream =new FileInputStream("/opt/xxx/conf/global_config.cfg")) {
        p = new Properties();
        p.load(stream);
        System.out.println(p.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return p;
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=300413&siteId=1