2016-04-18 8 views
0

クラスパスから自分の.propertiesファイルにアクセスする必要があります。現在私はリソースフォルダから直接アクセスしています。しかし、今私はクラスパスからそれにアクセスしたいです。Javaのクラスパスから.propertiesファイルをロード

現在のコード:

public void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException 
try { 
    properties.load(new FileInputStream(
      "src/resources/config.properties")); 
    for (String key : properties.stringPropertyNames()) { 
     String value = properties.getProperty(key); 
     rate.add(value); 
    } 
} 
} 

ファイルのパスは次のとおりです。私たちは完全なプロジェクトのwarファイルを作成しているコードを展開するためのsrc/resources/config.properties

このファイルをクラスパスから取得するにはどうすればよいかお勧めします。

答えて

0

あなたのconfig.propertiesファイルが使用しているJavaのあなたの同じパッケージ上に存在する場合は、ResourceBundle

+0

負荷で私はchagesを行う必要がありますか? – Developer

+0

このようにすることができます 'properties.load(this.getClass()。getClassLoader()。getResourceAsStream(" config.properties ")); ' – Wizbot

+0

nullポインタ例外のプロパティを取得しています.load(this.getClass()。 getClassLoader()。getResourceAsStream( "config.pr operties")); – Developer

0
final Properties properties = new Properties(); 
try (final InputStream stream = 
      this.getClass().getResourceAsStream("somefile.properties")) { 
    properties.load(stream); 
} 
+0

このコードは疑問に答えるかもしれませんが、いくつかの文脈を含めて、それがどのように動作し、いつ使用するかを説明する方がよいでしょう。コードのみの回答は長期的には有用ではありません。 – Bono

2

を使用することを検討すべきである.propertiesファイルを扱っている場合は、この

this.getClass().getClassLoader().getResourceAsStream("config.properties"); 

を使用して、クラスパスからファイルを読み込むことができますクラスを使用するだけで、

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties"); 

あなたは性質がどのパッケージにファイルを置く場合は、

にも
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/your_package_name/config.properties"); 

をパッケージ名を使用するので、競合コードが

try { 
    Properties configProperties = new Properties(); 
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("resources/config.properties"); 
    configProperties.load(inputStream); 
} 
catch(Exception e){ 
    System.out.println("Could not load the file"); 
    e.printStackTrace(); 
} 

UPDATE、のようにする:より良く理解するために は画像を参照してください。

enter image description here

+1

nullポインタ例外が発生しています。configProperties.load(inputStream); – Developer

+0

これは 'inputStream'が' null'であることを意味します。読み込めませんでした。あなたはプロパティファイルを置くスナップショットを表示できますか? –

+0

そこから戦争ファイルがあります.propファイルにアクセスしたいです – Developer

関連する問題